Skip to content

Instantly share code, notes, and snippets.


liorksh/Run TaskCompleteSource.cs Secret

Last active May 3, 2020
What would you like to do?
TaskCompleteSource example
public void RunTaskCompleteSourceTest()
TaskCompletionSource<FileInfo> taskCompletionSource = new TaskCompletionSource<FileInfo>();
Task<FileInfo> anotherTask = taskCompletionSource.Task;
Task fetchFileTask = Task.Factory.StartNew(()=>{
FileInfo fileInfo = new FileInfo(Directory.GetFiles(Environment.CurrentDirectory)[0]);
// Releasing the anotherTask.Result also be done by calling SetException or SetCancel
//taskCompletionSource.SetException(new InvalidOperationException("this action is illegal"));
// Will raise a TaskCanceledException since the task was canceled.
Task accessFileTask = Task.Factory.StartNew(() =>
// Calling the Result property is a blocking call; the thread continues after assigning the Result object,
// receiving an exception, or canceling the task.
FileInfo info = anotherTask.Result;
Trace.WriteLine($"Received file '{info.Name}, last modified {info.LastWriteTime}'");
// TODO: do something with the file
// Avoid exiting the test method before both tasks have finished
Task.WaitAll(fetchFileTask, accessFileTask);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.