Reputation: 4751
I'm starting to play around with .NET 4.5, especially the async/await features.
I came to the code below, which to my suprise, compiles. Can anyone explain to my why?
async Task SomeMethod()
{
try
{
await Task.Delay(1000);
}
catch
{
}
}
With previous .NET versions the compiler would complain with a message similar to: "not all of the paths return value".
Upvotes: 3
Views: 416
Reputation: 4632
In response to your question to Jon's answer, I add these links for better readability as a separate answer.
For getting more info on what happens behind the scenes I would like to point you these articles from the MSDN magazine that helped me getting started with it:
MSDN October 2011 issue: Parallel Programming with .NET
Especially the first two articles might be what you are looking for as they describe better how the compiler rewrites your code internally to make async/ await
work.
Upvotes: 1
Reputation: 1500665
An async method returning Task
is equivalent to a normal method returning void
. There's nothing try/catch-specific here - don't forget that your try
block doesn't return anything either!
So the non-async version of your code would just be:
void SomeMethod()
{
try
{
Thread.Sleep(1000)
}
catch
{
}
}
... and obviously that would compile. (Equally obviously, it's horrible to use use a bare catch
, but I assume that's not really the question :)
This code won't compile:
async Task<int> SomeMethod()
{
try
{
await Task.Delay(1000);
return 10;
}
catch
{
}
}
Upvotes: 5