且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在两个不同的线程上等待一项任务?

更新时间:2023-10-26 20:04:52

您可以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.