Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await for one task on two different threads?

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. Will the second thread wait for method Execute to finish executing?
  2. If it will, will I be able to re-use CurrentIteration for the same purpose in the second thread, given that I re-run

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

On the first thread?

I tried this code:

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);
    }
}

But it prints

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

then

thread 1 done!!

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

like image 271
nicks Avatar asked Mar 10 '23 10:03

nicks


1 Answers

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.

consider this:

    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.

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.

like image 151
CKII Avatar answered Mar 12 '23 23:03

CKII