gpt4 book ai didi

c# - 对 I/O 绑定(bind)操作使用异步函数

转载 作者:太空宇宙 更新时间:2023-11-03 22:32:22 25 4
gpt4 key购买 nike

我正在阅读这份文档 https://learn.microsoft.com/en-us/dotnet/csharp/async上面写着:

对于 I/O 绑定(bind)代码,您等待返回任务或异步方法内部任务的操作。

我有两个问题:

Q1- 对于 I/O 绑定(bind)代码,是否意味着我们需要使用 Task.Factory.StartNew(..., TaskCreationOptions.LongRunning)TaskCompletionSource

Q2- 我在下面编写了两个简单的控制台应用程序来模拟 I/O 绑定(bind)代码,我的方法是否正确?

class Program  //use Task.Factory.StartNew
{
static async Task Main(string[] args)
{
var task = ReadFile();
Console.WriteLine("Do other work");
int total = await task;
Console.WriteLine($"Read {total} lines");
Console.ReadLine();
}

static async Task<int> ReadFile()
{
return await Task.Factory.StartNew(new Func<int>(Read), TaskCreationOptions.LongRunning);
}

static int Read()
{
Thread.Sleep(5000); // simulate read operation
return 9999; // 9999 lines has been read
}
}

class Program  // use TaskCompletionSource
{
static void Main(string[] args)
{
var awaiter = ReadFile().GetAwaiter();
Console.WriteLine("Do other work");
awaiter.OnCompleted(() => Console.WriteLine($"Read {awaiter.GetResult()} lines"));
Console.ReadLine();
}

static Task<int> ReadFile()
{
var tcs = new TaskCompletionSource<int>();
new Thread(() =>
{
tcs.SetResult(Read());

}).Start();
return tcs.Task;
}

static int Read()
{
Thread.Sleep(5000); // simulate read operation
return 9999; // 9999 lines has been read
}
}

最佳答案

Q1- for I/O-bound code, does it mean we need to use Task.Factory.StartNew(..., TaskCreationOptions.LongRunning) or TaskCompletionSource

没有。

这意味着您使用asyncawait

Q2- I wrote a two simple console apps below to simulate I/O-bound code, is my approach correct?

没有。

I/O 本质上不是同步的,因此使用 Thread.Sleep 是 I/O 工作的错误替代。 I/O 本质上是异步的,因此适当的占位符是 await Task.Delay

class Program  // use async/await
{
static async Task Main(string[] args)
{
var task = ReadFileAsync();
Console.WriteLine("Do other work");
var result = await task;
Console.WriteLine($"Read {result} lines");
Console.ReadLine();
}

static async Task<int> ReadFileAsync()
{
await Task.Delay(5000); // simulate read operation
return 9999; // 9999 lines has been read
}
}

在一般 I/O 情况下,there is no thread .这就是为什么使用 Thread.Sleep 会抛出一切;当 I/O 不需要线程时,它会强制使用线程。

关于c# - 对 I/O 绑定(bind)操作使用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56844632/

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