使用async/await,什么时候继续发生?

Ash*_*ley 1 c# continuations async-await

我试图在一个非常大的已经存在的同步代码库中使用async/await.在这个代码库中有一些全局状态,如果是kludgy,在同步上下文中工作正常,但它在async/await的异步上下文中不起作用.

所以,我的两个选择似乎是要么分解全局上下文,这可能是一个非常大而且非常耗时的任务,或者在继续运行时做一些聪明的事情.

为了更好地理解async/await和continuations,我做了一个测试程序,如图所示.这里显示.

    // A method to simulate an Async read of the database.
    private static Task ReadAsync()
    {
        return Task.Factory.StartNew(() =>
        {
            int max = int.MaxValue / 2;
            for (int i = 0; i < max; ++i)
            {
            }
        });
    }

    // An async method that creates several continuations.
    private static async Task ProcessMany(int i)
    {
        Console.WriteLine(string.Format("{0} {1}", i.ToString(), 0));

        await ReadAsync();

        Console.WriteLine(string.Format("{0} {1}", i.ToString(), 1));

        await ReadAsync();

        Console.WriteLine(string.Format("{0} {1}", i.ToString(), 2));

        await ReadAsync();

        Console.WriteLine(string.Format("{0} {1}", i.ToString(), 3));
    }


    public static void Main(string[] args)
    {
        Queue<Task> queue = new Queue<Task>();

        for (int i = 0; i < 10; ++i)
        {
            queue.Enqueue(ProcessMany(i));
        }

        // Do some synchonous processing...
        Console.WriteLine("Processing... ");

        for (int i = 0; i < int.MaxValue; ++i)
        {
        }

        Console.WriteLine("Done processing... ");

        queue.Dequeue().Wait();
    }
Run Code Online (Sandbox Code Playgroud)

在阅读了所有关于async/await之后,我的理解是在"Processing .."和"Done processing ..."WriteLines之间不会发生任何延续.

这是一些示例输出.

0 0
1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
Processing...
3 1
2 1
7 1
6 1
0 1
4 1
5 1
1 1
6 2
3 2
Done processing...
7 2
2 2
0 2
4 2
5 2
1 2
6 3
3 3
7 3
2 3
0 3
Run Code Online (Sandbox Code Playgroud)

我希望程序结束时的单个Wait()在第一个完成时可能产生多个延续,但我不明白在"Processing ..."和"Done Processing"之间如何继续运行......".我以为在Console.WriteLine方法中可能有一个产量或者什么,所以我完全取代了它,但是这并没有改变输出.

我对async/await的理解显然存在差距.当我们简单地增加一个变量时,怎么会继续发生?编译器或CLR是否在这里注入某种魔力?

提前感谢您帮助更好地理解异步/等待和延续.

编辑:

如果你根据Stephen的评论以这种方式编辑示例代码,那么事情会更加明显.

    // An async method that creates several continuations.
    private static async Task ProcessMany(int i)
    {
        Console.WriteLine(string.Format("{0} {1} {2}", i.ToString(), 0, Thread.CurrentThread.ManagedThreadId));

        await ReadAsync();

        Console.WriteLine(string.Format("{0} {1} {2}", i.ToString(), 1, Thread.CurrentThread.ManagedThreadId));

        await ReadAsync();

        Console.WriteLine(string.Format("{0} {1} {2}", i.ToString(), 2, Thread.CurrentThread.ManagedThreadId));

        await ReadAsync();

        Console.WriteLine(string.Format("{0} {1} {2}", i.ToString(), 3, Thread.CurrentThread.ManagedThreadId));
    }


    public static void Main(string[] args)
    {
        Queue<Task> queue = new Queue<Task>();

        for (int i = 0; i < 10; ++i)
        {
            queue.Enqueue(ProcessMany(i));
        }

        // Do some synchonous processing...
        Console.WriteLine("Processing... {0}", Thread.CurrentThread.ManagedThreadId);

        for (int i = 0; i < int.MaxValue; ++i)
        {
        }

        Console.WriteLine("Done processing... {0}", Thread.CurrentThread.ManagedThreadId);

        queue.Dequeue().Wait();
    }
Run Code Online (Sandbox Code Playgroud)

输出:

0 0 9
1 0 9
2 0 9
3 0 9
4 0 9
5 0 9
6 0 9
7 0 9
8 0 9
9 0 9
Processing... 9
4 1 14
3 1 13
2 1 12
5 1 15
0 1 10
6 1 16
1 1 11
7 1 17
4 2 14
3 2 13
0 2 10
6 2 16
2 2 12
5 2 15
Done processing... 9
1 2 11
7 2 17
0 3 10
4 3 14
Run Code Online (Sandbox Code Playgroud)

Ste*_*ary 5

如果您没有当前SynchronizationContextTaskScheduler,则继续将在线程池线程(与主线程分开)上执行.在控制台应用程序中就是这种情况,但您会在WinForms/WPF/ASP.NET中看到非常不同的行为.

虽然您可以通过使用自定义控制延续计划TaskScheduler,但这可能是相当多的工作,可能只有很少的好处.我不清楚你的全球国家的问题是什么,但考虑诸如此类的替代方案SemaphoreSlim.