Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Task<int> RunTaskCompletionSourceExample(int number)
- {
- var taskCompletionSource = new TaskCompletionSource<int>();
- // Simulate some work
- Task.Run(() =>
- {
- if (number >= 0)
- {
- // When work completes successfully, set the result.
- taskCompletionSource.SetResult(number * 2);
- }
- else
- {
- // If there is an error, we can set the exception.
- taskCompletionSource.SetException(new Exception("Input should be a non-negative number"));
- }
- });
- return taskCompletionSource.Task;
- }
- try
- {
- //Await the task
- int result = await RunTaskCompletionSourceExample(5);
- Console.WriteLine("Result is: " + result);
- }
- catch (Exception ex)
- {
- Console.WriteLine("Error: " + ex.Message);
- }
- 25/July/2023
- ---
- Singleton Sean has a nice yotuube video where he also talk about TaskCompletionSource
- https://youtu.be/vYXs--S0Xxo 6:20
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement