0

I have been searching for a quite time but I can't seem to find a solution for my code. How can I handle the exception when it goes to the if (e.Error != null) condition, by other words, when something wrong happens with the async call?

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;
    }

And this is how I call it in my main:

var client = new StorageClient();
var providers_data = await client.GetAllProvidersTask();

I followed this example to write my code: How can I use async/await to call a webservice?

Community
  • 1
  • 1
sparcopt
  • 416
  • 2
  • 8
  • 22

1 Answers1

0

You add a try block around the statement containing the await expression:

try
{
  var client = new StorageClient();
  var providers_data = await client.GetAllProvidersTask();
}
catch (Exception ex)
{
  ...
  throw;
}
Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • Yes, I already tried this and it works. But the problem here is that I still get that warning from Visual Studio saying that there is a exception coming from the line `var providers_data = await client.GetAllProvidersTask();` that is not user handled. Here is the image: http://snag.gy/AhGmy.jpg How to solve this? – sparcopt Jun 13 '13 at 19:02
  • I don't have much WP experience, but I would try Debug -> Exceptions and uncheck all the "Thrown" boxes. – Stephen Cleary Jun 13 '13 at 19:28