小编Wym*_*n.W的帖子

在c#的异步/等待的控制流中感到困惑

我正在学习async/await,并对MSDN的await的解释感到困惑:" await运算符暂停执行,直到GetByteArrayAsync方法的工作完成.同时,控制权返回给GetPageSizeAsync的调用者 "

我不明白的是,"返回"是什么意思?起初,我相信当一个线程(比方说,UI线程)到达"await"关键字时,系统将创建一个新线程(或从threadPool获取一个线程)来执行其余的代码,并且UI线程可以返回调用方法并执行其余的操作.

但现在我知道"等待"永远不会创造线程.

我写了一个演示:

class Program
{
    static void Main(string[] args)
    {
        new Test().M1();
        Console.WriteLine("STEP:8");
        Console.Read();
    }
}

class Test
{
    public async void M1()
    {
        Console.WriteLine("STEP:1");
        var t = M2();
        Console.WriteLine("STEP:3");
        await t;
    }
    public async Task<string> M2()
    {
        Console.WriteLine("STEP:2");
        string rs = await M3();//when the thread reaches here,why don't it return to M1 and execute the STEP:3 ??
        Console.WriteLine("STEP:7");
        return rs;

    }

    public async Task<string> M3()
    {
        Console.WriteLine("STEP:4");
        var rs = Task.Run<string>(() => { …
Run Code Online (Sandbox Code Playgroud)

c# async-await

3
推荐指数
1
解决办法
329
查看次数

标签 统计

async-await ×1

c# ×1