gpt4 book ai didi

c# - .NET Async 中的可伸缩性与响应能力

转载 作者:太空狗 更新时间:2023-10-29 19:59:46 24 4
gpt4 key购买 nike

我正在通读 Exam Ref 70-483: Programming in C#本书并给出了以下代码示例:

list 1-19

public Task SleepAsyncA(int millisecondsTimeout)
{
return Task.Run(() => thread.Sleep(millisecondsTimeout);
}

public Task SleepAsyncB(int millisecondsTimeout)
{
TaskCompletionSource<bool> tcs = null;
var t = new Timer(delegate { tcs.TrySetResult(true); }, -1, -1);
tcs = new TaskCompletionSource<bool>(t);
t.Change(millisecondsTimeout, -1);
return tcs.Task;
}

下面的段落说明了这一点:

The SleepAsyncA method uses a thread from the thread pool while sleeping. the second method, however, which has a completely different implementation, does not occupy a thread while waiting for the timer to run. The second method gives you scalability.

为什么 A 是响应式的而 B 是可扩展的?

最佳答案

假设起点没有进程/线程/任务控制并且是一个无响应的自旋循环,检查时间是否已经过去,例如:

public void SleepBadly(int millisecondsTimeout)
{
var stopTime = DateTime.UtcNow.AddMilliseconds(millisecondsTimeout);
while (DateTime.UtcNow < stopTime) {}
return;
}

SleepAsyncA 使线程休眠而不是旋转,因此它不使用任何 CPU,因此会响应,因为 CPU 可用,但它仍在使用线程在它 sleep 的时候。

SleepAsyncB 在等待时放弃线程,因此它不使用 CPU,该线程可用于其他用途;因此它响应迅速并且可扩展

例如,在规模上,如果您在 SleepAsyncA 中有 100,000 个未完成的调用;要么你会耗尽线程池,它们会开始排队,要么你会有 100,000 个事件线程,这两种情况都不利于可伸缩性。

另一方面,SleepAsyncB 将使用 0 个线程,而 100,000 个调用正在等待,什么都不做比做某事更具可扩展性。

但是,虽然 SleepAsyncB 是一个很好的示例,说明如何使用 TaskCompletionSource 等任务构造,但在此示例中您实际可能想要做的是:

public Task SleepAsyncC(int millisecondsTimeout)
{
return Task.Delay(millisecondsTimeout);
}

关于c# - .NET Async 中的可伸缩性与响应能力,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20848679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com