简体   繁体   中英

Strange try..catch behaviour with async

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".

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
    {

    }
}

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

  1. Pause and Play with Await
  2. Async Performance: Understanding the Costs of Async and Await
  3. Easier Asynchronous Programming with the New Visual Studio Async CTP

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM