简体   繁体   中英

How can I notify awaiting Task from another thread to complete?

Consider following pseudocode:

Thread #1

var task = new Task<int>();
this.AwaitingTask = task;
return await task;

Thread #2

this.AwaitingTask.Complete(16);

This way, #2 thread would pass return value (int) and notify that Task is completed. So the #1 thread would know to continue execution.

Is it possible to implement? And how? I'm looking for closest idea that would work in similiar way.

You don't have to implement it. It is already shipped with name TaskCompletionSource<T>

Thread 1

var completionSource = new TaskCompletionSource<int>();
this.CompletionSource= completionSource;
return await completionSource.Task;

Thread 2

this.CompletionSource.SetResult(16);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM