我一直在寻找相当长的时间,但我似乎无法为我的代码找到解决方案。
当它进入if (e.Error != null)
条件时,我怎么能处理异常,换句话说,当异步调用出现错误时?
private static StorageClient client = new StorageClient();
private static void TransferCompletion<T>(TaskCompletionSource<T> tcs, System.ComponentModel.AsyncCompletedEventArgs e, Func<T> getResult)
{
if (e.Error != null)
{
MessageBox.Show("1");
tcs.TrySetException(e.Error);
}
else if (e.Cancelled)
{
MessageBox.Show("2");
tcs.TrySetCanceled();
}
else
{
MessageBox.Show("3");
tcs.TrySetResult(getResult());
}
}
public static Task<getAllProvidersCompletedEventArgs> GetAllProvidersTask(this StorageClient client)
{
var tcs = new TaskCompletionSource<getAllProvidersCompletedEventArgs>();
client.getAllProvidersCompleted += (s, e) => TransferCompletion(tcs, e, () => e);
client.getAllProvidersAsync();
return tcs.Task;
}
这就是我在主打中所说的:
var client = new StorageClient();
var providers_data = await client.GetAllProvidersTask();
我按照这个例子编写了我的代码:How can I use async/await to call a webservice?
答案 0 :(得分:0)
在包含try
表达式的语句周围添加await
块:
try
{
var client = new StorageClient();
var providers_data = await client.GetAllProvidersTask();
}
catch (Exception ex)
{
...
throw;
}