使用await 处理非CPU 密集型任务

发布于 2024-10-14 10:37:10 字数 506 浏览 5 评论 0原文

我有这样的事情:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

辞取 2024-10-21 10:37:10

我认为您在这里误解了任务异步模式的意图。您正在做的事情可能最好由 处理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".

墨离汐 2024-10-21 10:37:10

这取决于您正在执行的任务。既然你说它不使用大量 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文