- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我对 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();
}
但他们没有!
完整程序如下:
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);
}
}
}
这是输出:
[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 ...
我错过了什么?
最佳答案
async-await
针对您正在等待的任务已经完成的时间进行优化(当您将信号量设置为 10 而只有 1 个线程使用它时就是这种情况)。在那种情况下,线程只是同步进行。
您可以看到,通过向 RunAsync
添加一个实际的异步操作并查看它如何改变正在使用的线程池线程(这将是当您的信号量为空并且调用者实际需要异步等待):
public static async Task RunAsync(SemaphoreSlim sem)
{
TraceThreadCount();
await Task.Delay(1000);
await sem.WaitAsync();
TraceThreadCount();
sem.Release();
}
您还可以对 Run
进行此更改,并让它同步执行延续并获得与 RunAsync
相同的结果(线程计数方面):
public static Task Run(SemaphoreSlim sem)
{
TraceThreadCount();
return sem.WaitAsync().ContinueWith(t =>
{
TraceThreadCount();
sem.Release();
}, TaskContinuationOptions.ExecuteSynchronously);
}
输出:
[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 ...
重要说明:当说 async-await
充当延续时,它更像是一个类比。这些概念之间存在几个关键差异,尤其是关于 SynchronizationContext
。 async-await
自动保留当前上下文(除非您指定 ConfigureAwait(false)
),因此您可以在重要的环境(UI、ASP.Net 等)中安全地使用它.).关于同步上下文的更多信息 here .
此外,await Task.Delay(1000);
可以替换为 await Task.Yield();
说明时间无关紧要,只是方法异步等待这一事实很重要。 Task.Yield()
在异步代码的单元测试中通常很有用。
关于c# - SemaphoreSlim.WaitAsync 延续代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25654498/
我试图找出在这种上下文中使用的 Wait 和 WaitAsync 的 SemaphoreSlim 使用之间的区别: private SemaphoreSlim semaphore = new Sema
我对 await 关键字的理解是,await 限定语句之后的代码在完成后作为该语句的延续运行。 因此以下两个版本应该产生相同的输出: public static Task Run(Semaph
SemaphoreSlim 的文档说“只有在所有其他操作都已完成时才应使用 Dispose”。 应该如何调整以下类,以便线程 B 可以在线程 A 等待 Async() 时调用 Dispose()。调用
首先,请原谅我的英语。我将在 Task.WhenAny 之后的附加代码中进行简要说明,我期望的是五个任务中至少有三个将被取消,但都圆满结束。当任务被取消时,SemaphoreSlim.WaitAsyn
我的应用程序正在使用 .NET 4。我正在使用 nuget package 来等待异步 在我的应用程序中,我想按如下方式在 sempahore WaitAsync 调用上进行等待。 Semaphore
我知道在同步世界中第一个片段是正确的,但是 WaitAsync 和 async/await 魔法又是什么呢?请给我一些 .net 内部信息。 await _semaphore.WaitAsync();
SemaphoreSlim.WaitAsync不管用。它跳转到 return currentToken.AccessToken之前GetAccesTokenAsync调用它已完成并抛出 NullExc
我是一名优秀的程序员,十分优秀!