0

我一直在寻找相当长的时间,但我似乎无法为我的代码找到解决方案。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();

我按照这个例子编写了我的代码:如何使用 async/await 来调用 web 服务?

4

1 回答 1

0

您在包含表达式的语句周围添加一个try块:await

try
{
  var client = new StorageClient();
  var providers_data = await client.GetAllProvidersTask();
}
catch (Exception ex)
{
  ...
  throw;
}
于 2013-06-13T17:26:43.453 回答