Skip to content

Instantly share code, notes, and snippets.

@liorksh

liorksh/Run TaskCompleteSource.cs Secret

Last active May 3, 2020
Embed
What would you like to do?
TaskCompleteSource example
[Fact]
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]);
taskCompletionSource.SetResult(fileInfo);
// 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.
//taskCompletionSource.SetCanceled();
});
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.