SemaphoreSlim.WaitAsync延续代码

mar*_*ark 4 .net c# multithreading asynchronous async-await

我对该await关键字的理解是,该await语句后面的代码在完成后作为该语句的延续运行.

因此,以下两个版本应该产生相同的输出:

    public static Task Run(SemaphoreSlim sem)
    {
        TraceThreadCount();
        return sem.WaitAsync().ContinueWith(t =>
        {
            TraceThreadCount();
            sem.Release();
        });
    }

    public static async Task RunAsync(SemaphoreSlim sem)
    {
        TraceThreadCount();
        await sem.WaitAsync();
        TraceThreadCount();
        sem.Release();
    }
Run Code Online (Sandbox Code Playgroud)

但他们没有!

这是完整的程序:

using System;
using System.Threading;
using System.Threading.Tasks;

namespace CDE
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                var sem = new SemaphoreSlim(10);
                var task = Run(sem);

                Trace("About to wait for Run.");

                task.Wait();

                Trace("--------------------------------------------------");
                task = RunAsync(sem);

                Trace("About to wait for RunAsync.");

                task.Wait();
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
            }
            Trace("Press any key ...");
            Console.ReadKey();
        }

        public static Task Run(SemaphoreSlim sem)
        {
            TraceThreadCount();
            return sem.WaitAsync().ContinueWith(t =>
            {
                TraceThreadCount();
                sem.Release();
            });
        }

        public static async Task RunAsync(SemaphoreSlim sem)
        {
            TraceThreadCount();
            await sem.WaitAsync();
            TraceThreadCount();
            sem.Release();
        }

        private static void Trace(string fmt, params object[] args)
        {
            var str = string.Format(fmt, args);
            Console.WriteLine("[{0}] {1}", Thread.CurrentThread.ManagedThreadId, str);
        }
        private static void TraceThreadCount()
        {
            int workerThreads;
            int completionPortThreads;
            ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
            Trace("Available thread count: worker = {0}, completion port = {1}", workerThreads, completionPortThreads);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

[9] Available thread count: worker = 1023, completion port = 1000
[9] About to wait for Run.
[6] Available thread count: worker = 1021, completion port = 1000
[9] --------------------------------------------------
[9] Available thread count: worker = 1023, completion port = 1000
[9] Available thread count: worker = 1023, completion port = 1000
[9] About to wait for RunAsync.
[9] Press any key ...
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

i3a*_*non 6

async-await优化您正在等待的任务何时已经完成(当您将信号量设置为10且只有1个线程使用它时).在这种情况下,线程只是同步进行.

您可以通过添加实际的异步操作来RunAsync查看它,并查看它如何更改正在使用的线程池线程(当您的信号量为空且调用者实际需要异步等待时,这将是行为):

public static async Task RunAsync(SemaphoreSlim sem)
{
    TraceThreadCount();
    await Task.Delay(1000);
    await sem.WaitAsync();
    TraceThreadCount();
    sem.Release();
}
Run Code Online (Sandbox Code Playgroud)

您也可以进行此更改Run并使其同步执行延续,并获得与您的RunAsync(线程计数)相同的结果:

public static Task Run(SemaphoreSlim sem)
{
    TraceThreadCount();
    return sem.WaitAsync().ContinueWith(t =>
    {
        TraceThreadCount();
        sem.Release();
    }, TaskContinuationOptions.ExecuteSynchronously);
}
Run Code Online (Sandbox Code Playgroud)

输出:

[1] Available thread count: worker = 1023, completion port = 1000  
[1] Available thread count: worker = 1023, completion port = 1000  
[1] About to wait for Run.  
[1] --------------------------------------------------  
[1] Available thread count: worker = 1023, completion port = 1000  
[1] Available thread count: worker = 1023, completion port = 1000  
[1] About to wait for RunAsync.  
[1] Press any key ...  
Run Code Online (Sandbox Code Playgroud)

重要提示:当它被认为async-await是一个延续时,它更像是一个类比.这些概念之间有几个关键的区别,特别是关于SynchronizationContexts.async-await自动保留当前上下文(除非您指定ConfigureAwait(false)),以便您可以在重要的环境(UI,ASP.Net等)中安全地使用它.更多关于同步的环境在这里.