Is it possible to call Wait()
on the same Task
from two different threads at the same time?
For example, is the following code valid:
private BlockingCollection<Task> _queue = new BlockingCollection<Task>();
private Thread _taskPumpThread;
...
private void Run()
{
_taskPumpThread= new Thread(() => TaskPump(...));
_taskPumpThread.Start();
DoNothing();
}
private void DoNothing()
{
Task doNothing = new Task(() => Console.WriteLine("Doing nothing"));
queue.Add(doNothing);
doNothing.Wait(); // no try-catch for brevity
}
private void TaskPump(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
Task task = queue.Take();
task.Start();
task.Wait();
}
}
Motivation:
I'm implementing a controller which ultimately serialized requests to a serial port, and handles notifications from the port. The requests can be sent from different threads, and they should be able to wait for a result (or an exception), but can opt to work asynchronously.
I'm considering the design above, as Task
s nicely handle all cases (synchronous result, async calls and exceptions).
A related, though not identical, question, can be found here .
I'll limit myself to answering your very specific question.
If you run the following short program you'll see that the answer is yes , you can have multiple threads wait on the same task:
public static void Main(string[] args)
{
Task t = Task.Delay(10000);
new Thread(() => { ThreadRun(t); }).Start();
new Thread(() => { ThreadRun(t); }).Start();
Console.WriteLine("Main thread exits"); // this prints immediately.
}
private static void ThreadRun(Task t)
{
t.Wait();
Console.WriteLine(Thread.CurrentThread.ManagedThreadId + " finished waiting"); // this prints about 10 seconds later.
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.