Alex Rivera | Logout

Await in catch block

Asked 2012-01-15T07:09:15.737
88

I have the following code:

WebClient wc = new WebClient();
string result;
try
{
  result = await wc.DownloadStringTaskAsync( new Uri( "http://badurl" ) );
}
catch
{
  result = await wc.DownloadStringTaskAsync( new Uri( "http://fallbackurl" ) );
}

Basically I want to download from a URL and when it fails with an exception I want to download from another URL. Both time async of course. However the code does not compile, because of

error CS1985: Cannot await in the body of a catch clause

OK, it's forbidden for whatever reason but what's the correct code pattern here?

EDIT:

The good news is that C# 6.0 will likely allow await calls both in catch and finally blocks.

Edit
Report

1 Answer

9

This seems to work.

        WebClient wc = new WebClient();
        string result;
        Task<string> downloadTask = wc.DownloadStringTaskAsync(new Uri("http://badurl"));
        downloadTask = downloadTask.ContinueWith(
            t => {
                return wc.DownloadStringTaskAsync(new Uri("http://google.com/")).Result;
            }, TaskContinuationOptions.OnlyOnFaulted);
        result = await downloadTask;
answered 2012-10-27T15:55:41.143

Your Answer