Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await in catch block

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.

like image 323
György Balássy Avatar asked Jan 15 '12 07:01

György Balássy


People also ask

Can you await in a catch block?

C# await is a keyword. It is used to suspend execution of the method until the awaited task is complete. In C# 6.0, Microsoft added a new feature that allows us to use await inside the catch or finally block. So, we can perform asynchronous tasks while exception is occurred.

Can we write async in catch block?

Now finally we can use await statements and async methods with catch {} and finally {} blocks without writing complicated code.

Should await always be in try catch?

No. You don't need to use try/catch in every async/await. You only need to do it at the top level.


2 Answers

Update: C# 6.0 supports await in catch


Old Answer: You can rewrite that code to move the await from the catch block using a flag:

WebClient wc = new WebClient(); string result = null; bool downloadSucceeded; try {   result = await wc.DownloadStringTaskAsync( new Uri( "http://badurl" ) );   downloadSucceeded = true; } catch {   downloadSucceeded = false; }  if (!downloadSucceeded)   result = await wc.DownloadStringTaskAsync( new Uri( "http://fallbackurl" ) ); 
like image 170
svick Avatar answered Oct 09 '22 03:10

svick


Awaiting in a catch block is now possible as of the End User Preview of Roslyn as shown here (Listed under Await in catch/finally) and will be included in C# 6.

The example listed is

try … catch { await … } finally { await … } 

Update: Added newer link, and that it will be in C# 6

like image 41
Craig Avatar answered Oct 09 '22 02:10

Craig