-
-
Save liorksh/684bd3f975aefcd42837ef9b7c76b1de to your computer and use it in GitHub Desktop.
TaskCompleteSource example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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