Advertisement
Guest User

Untitled

a guest
Jun 16th, 2019
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.90 KB | None | 0 0
  1. private void StartBackgroundTasks(CancellationTokenSource cancelTokenSrc)
  2. {
  3. void TaskAction()
  4. {
  5. DoWork();
  6. }
  7.  
  8. void HeartbeatAction()
  9. {
  10. var task = TaskFactory.CreateAndStartLongRunningTask(
  11. TaskAction, cancelTokenSrc.Token);
  12.  
  13. while (true)
  14. {
  15. // checks Task.Status to figure out when to stop
  16. if (!TryPerformHeartbeat(task)) break;
  17.  
  18. Task.Delay(TimeSpan.FromSeconds(20)).Wait();
  19. }
  20. }
  21.  
  22. TaskFactory.CreateAndStartLongRunningTask(HeartbeatAction);
  23. }
  24.  
  25. internal static class TaskFactory
  26. {
  27. internal static Task CreateAndStartLongRunningTask(
  28. Action action, CancellationToken? token = null)
  29. {
  30. return Task.Factory.StartNew(
  31. action,
  32. token ?? CancellationToken.None,
  33. TaskCreationOptions.LongRunning,
  34. TaskScheduler.Default);
  35. }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement