Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

.net - Async/ Await: why does the code that follows await is also executed on the background thread and not on the original primary thread?

Below is my code:

class Program
{
    static async Task Main(string[] args)
    {
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
        string message = await DoWorkAsync();
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine(message);
    }

    static async Task<string> DoWorkAsync()
    {
        return await Task.Run(() =>
        {
            Thread.Sleep(3_000);
            return "Done with work!";
        });
    }
}

and the output is

1

// after 3 secs

3

Done with work!

so you can see the main thread(id is 1) changed to worker thread(id is 3), so how come the main thread just disappear?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The asynchronous entry point is just a compiler trick. Behind the scenes, the compiler generates this real entry point:

private static void <Main>(string[] args)
{
    _Main(args).GetAwaiter().GetResult();
}

If you change your code to be like this:

class Program
{
    private static void Main(string[] args)
    {
        MainAsync(args).GetAwaiter().GetResult();
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
    }


    static async Task MainAsync(string[] args)
    {
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
        string message = await DoWorkAsync();
        Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
        Console.WriteLine(message);
    }

    static async Task<string> DoWorkAsync()
    {
        await Task.Delay(3_000);
        return "Done with work!";
    }
}

You'll get this:

1
4
Done with work!
1

As expected, the main thread is waiting for the work to be done.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...