使用await 处理非CPU 密集型任务
我有这样的事情:
private void DoSomething()
{
System.Console.WriteLine("Creating Foo");
Foo result = new Foo();
DoSomethingAsync();
System.Console.WriteLine("Returning Foo");
return result;
}
private async void DoSomethingAsync()
{
// The following task takes a long time, but is not CPU intensive
await TaskEx.Run(() =>
{
// code lives here... removed for this example
});
}
由于我对CPU的影响不大,所以我不需要线程。我可以使用什么来代替 Run 来避免创建线程?
I have something like this:
private void DoSomething()
{
System.Console.WriteLine("Creating Foo");
Foo result = new Foo();
DoSomethingAsync();
System.Console.WriteLine("Returning Foo");
return result;
}
private async void DoSomethingAsync()
{
// The following task takes a long time, but is not CPU intensive
await TaskEx.Run(() =>
{
// code lives here... removed for this example
});
}
Since I don't hit the CPU much, I don't need a thread. What can I use instead of Run to avoid the creation of a thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您在这里误解了任务异步模式的意图。您正在做的事情可能最好由
处理ThreadPool.QueueUserWorkItem
它将重用进程池中的工作线程,仅在必要时创建一个。TAP 允许您将任务分解为可以增量处理的工作“块”,但它不直接提供一种方法来表示“这是后台任务”。
I think you're misunderstanding the intent of the Task Asynchrony Pattern here. What you're doing is probably better handled by
ThreadPool.QueueUserWorkItem
which will reuse a worker thread from the process's pool, only creating one if necessary.The TAP allows you to break a task into "chunks" of work that can be processed incrementally, but it does not directly provide a means to say "this is a background task".
这取决于您正在执行的任务。既然你说它不使用大量 CPU,我会假设该任务需要很长时间,因为它正在等待其他事件。因此,您需要设计任务来注册这些事件的回调,其中每个回调在主线程上快速完成,但直到您正在等待的事件实际发生时才会触发。
It depends on the task that you're doing. Since you say that it doesn't use a lot of CPU, I'll assume the task takes a long time because it's waiting for other events. So, you'll need to design your task to register callbacks for those events, where each callback completes quickly on the main thread, but isn't triggered until the event you're awaiting actually occurs.