Advertisement
ivandrofly

TaskCompletionSource Example

Jul 17th, 2023 (edited)
1,376
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.96 KB | None | 0 0
  1. Task<int> RunTaskCompletionSourceExample(int number)
  2. {
  3.     var taskCompletionSource = new TaskCompletionSource<int>();
  4.        
  5.     // Simulate some work
  6.     Task.Run(() =>
  7.     {
  8.         if (number >= 0)
  9.         {
  10.             // When work completes successfully, set the result.
  11.             taskCompletionSource.SetResult(number * 2);
  12.         }
  13.         else
  14.         {
  15.             // If there is an error, we can set the exception.
  16.             taskCompletionSource.SetException(new Exception("Input should be a non-negative number"));
  17.         }
  18.     });
  19.        
  20.     return taskCompletionSource.Task;
  21. }
  22.  
  23. try
  24. {
  25.     //Await the task
  26.     int result = await RunTaskCompletionSourceExample(5);
  27.     Console.WriteLine("Result is: " + result);
  28. }
  29. catch (Exception ex)
  30. {
  31.     Console.WriteLine("Error: " + ex.Message);
  32. }
  33.  
  34.  
  35. 25/July/2023
  36. ---
  37. Singleton Sean has a nice yotuube video where he also talk about TaskCompletionSource
  38. https://youtu.be/vYXs--S0Xxo 6:20
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement