gpt4 book ai didi

c# - 了解没有线程的异步/等待

转载 作者:太空狗 更新时间:2023-10-29 23:46:30 27 4
gpt4 key购买 nike

<分区>

According to MSDN , asyncawait 不创建新线程:

The async and await keywords don't cause additional threads to be created.

考虑到这一点,我很难理解一些简单程序的控制流程。我的完整示例如下。请注意,它需要 Dataflow library ,您可以从 NuGet 安装它。

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

namespace TaskSandbox
{
class Program
{
static void Main(string[] args)
{
BufferBlock<int> bufferBlock = new BufferBlock<int>();

Consume(bufferBlock);
Produce(bufferBlock);

Console.ReadLine();
}

static bool touched;
static void Produce(ITargetBlock<int> target)
{
for (int i = 0; i < 5; i++)
{
Console.Error.WriteLine("Producing " + i);
target.Post(i);
Console.Error.WriteLine("Performing intensive computation");
touched = false;
for (int j = 0; j < 100000000; j++)
;
Console.Error.WriteLine("Finished intensive computation. Touched: " + touched);
}

target.Complete();
}

static async void Consume(ISourceBlock<int> source)
{
while (await source.OutputAvailableAsync())
{
touched = true;
int received = source.Receive();
Console.Error.WriteLine("Received " + received);
}
}
}
}

输出:

Producing 0
Performing intensive computation
Received 0
Finished intensive computation. Touched: True
Producing 1
Performing intensive computation
Received 1
Finished intensive computation. Touched: True
Producing 2
Performing intensive computation
Received 2
Finished intensive computation. Touched: False
Producing 3
Performing intensive computation
Received 3
Finished intensive computation. Touched: False
Producing 4
Performing intensive computation
Received 4
Finished intensive computation. Touched: True

这似乎表明 Consumefor 循环运行时获得控制权,因为 OutputAvailableAsync 任务完成:

for (int j = 0; j < 100000000; j++)
;

这在线程模型中不足为奇。但是,如果不涉及额外的线程,Produce 如何在 for 循环中间产生控制权?

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