如何在两个不同的线程上等待一项任务? [英] How to await for one task on two different threads?

查看:65
本文介绍了如何在两个不同的线程上等待一项任务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以等待在其他线程上创建的任务吗?例如:

Can I await on a Task that was created on a different thread? For example:

...
CurrentIteration = Execute(); // returns Task
await CurrentIteration;
...

然后,在另一个线程上:

And then, on another thread:

...
await CurrentIteration;
...

  1. 第二个线程是否将等待方法Execute完成执行?
  2. 如果可以的话,假设我重新运行,我将能够在第二个线程中出于相同的目的重用CurrentIteration

CurrentIteration = Execute(); // returns Task await CurrentIteration;

CurrentIteration = Execute(); // returns Task await CurrentIteration;

在第一个线程上?

我尝试了以下代码:

public class Program
{
    public static void Main(string[] args)
    {
        MainAsync(args).GetAwaiter().GetResult();
    }
    public static async Task MainAsync(string[] args)
    {

        var instance = new SomeClass();
        var task = instance.Execute();
        Console.WriteLine("thread 1 waiting...");
        Task.Run(async () =>
        {
            Console.WriteLine("thread 2 started... waiting...");
            await task;
            Console.WriteLine("thread 2 ended!!!!!");
        });

        await task;

        Console.WriteLine("thread 1 done!!");

        Console.ReadKey();
    }
}


public class SomeClass
{
    public async Task Execute()
    {
        await Task.Delay(4000);
    }
}

但是可以打印

thread 1 waiting...
thread 2 started... waiting...

然后

thread 1 done!!

,但从不thread 2 ended!!!!!.这是为什么?我该如何实现?谢谢!

but never thread 2 ended!!!!!. Why is that? How can I achieve that? Thanks!

推荐答案

您可以await从多个线程处理一个任务.正如@Rob所说,实际上您真的很接近要起作用,您只需要await第二个线程.

You can await on a task from multiple threads. You were actually really close to get that to work, as @Rob said, you just needed to await the second thread.

考虑这一点:

    public static async Task MainAsync(string[] args)
    {

        var instance = new SomeClass();
        var task = instance.Execute();
        Console.WriteLine("thread 1 waiting...");
        var secondTask = Task.Run(async () =>
        {
            Console.WriteLine("thread 2 started... waiting...");
            await task;
            Console.WriteLine("thread 2 ended!!!!!");
        });

        await task;

        await secondTask;

        Console.WriteLine("thread 1 done!!");

        Console.ReadKey();
    }

在等待任务完成后,在第二个线程上添加等待.

Add the wait on your second thread after you finish waiting for the task.

您没有看到指示的原因是因为控制台卡在了ReadKey方法上,并且在完成之前无法编写任何内容.如果您按Enter键,则会看到线程2已结束!!!!!!"在应用程序关闭之前等待一秒钟.

The reason you didn't see the indication is because the console got stuck on the ReadKey method, and couldn't write anything until it's finished. If you would've pressed Enter, you can see the "thread 2 ended!!!!!" line for a second before the app closes.

这篇关于如何在两个不同的线程上等待一项任务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆