Skip to content

Instantly share code, notes, and snippets.

@liorksh
Last active May 3, 2020 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liorksh/684bd3f975aefcd42837ef9b7c76b1de to your computer and use it in GitHub Desktop.
Save liorksh/684bd3f975aefcd42837ef9b7c76b1de to your computer and use it in GitHub Desktop.
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