Guest User

Untitled

a guest
Nov 20th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. void TestTimeOut()
  2. {
  3. var cts = new CancellationTokenSource();
  4. cts.CancelAfter(5000);
  5.  
  6. try
  7. {
  8. var task = Task.Run(() => LongRunningOperation(cts.Token));
  9. task.ContinueWith(t => Console.WriteLine("Operation cancelled"), TaskContinuationOptions.OnlyOnFaulted);
  10. task.Wait();
  11. }
  12. catch (AggregateException e)
  13. {
  14. //Handle
  15. }
  16. }
  17.  
  18.  
  19. void LongRunningOperation(CancellationToken token)
  20. {
  21. CancellationTokenRegistration registration = token.Register(
  22. () =>
  23. {
  24. throw new OperationCanceledException(token);
  25. });
  26.  
  27. using (registration)
  28. {
  29. // long running operation here
  30. }
  31. }
  32.  
  33. static void LongRunningOperation(CancellationToken token)
  34. {
  35. TaskCompletionSource<int> tcs1 = new TaskCompletionSource<int>();
  36. token.Register(() => { tcs1.TrySetCanceled(token); });
  37. Task.Run(() =>
  38. {
  39. // long running operation here
  40. Thread.Sleep(5000);
  41. tcs1.TrySetResult(0);
  42. }, token);
  43. tcs1.Task.Wait();
  44. }
Add Comment
Please, Sign In to add comment