Want more features on Pastebin? Sign Up, it's FREE!
Guest

Untitled

By: a guest on Dec 10th, 2012  |  syntax: None  |  size: 1.78 KB  |  views: 16  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. class Main
  2. {
  3.     void test()
  4.     {
  5.         TaskScheduler scheduler = TaskScheduler.FromCurrentSynchronizationContext();
  6.  
  7.         var runTask = new RunTask();
  8.         var task = runTask.CreateTask(doSomething, scheduler)
  9.                 .ContinueWith<bool>(..., scheduler);
  10.         task.Wait();
  11.     }
  12. }
  13.  
  14. public class RunTask
  15. {
  16.     public RunTask()
  17.     {
  18.     }
  19.  
  20.     public Task CreateTask(Action action, TaskScheduler scheduler)
  21.     {
  22.         _scheduler = scheduler;
  23.         return Task.Factory.StartNew(() => executeAction(action), CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);
  24.     }
  25.  
  26.     private void executeAction(Action action)
  27.     {
  28.         var t1 = Task.Factory
  29.            .StartNew(action)
  30.            .ContinueWith<Task>(mainTaskCompleted);
  31.  
  32.         var t2 = Task.Factory
  33.             .StartNew<bool>(waitMainTask)
  34.             .ContinueWith(progressTaskCompleted, _scheduler);//progressTaskCompleted - show and hide progress operation in UI
  35.  
  36.         var tasks = new[] {t1, t2};
  37.         Task.WaitAll(tasks);
  38.  
  39.         if (t1.Result.IsFaulted)
  40.         {
  41.             throw t1.Result.Exception;
  42.         }
  43.     }
  44.  
  45.     private bool waitMainTask()
  46.     {
  47.         var showProgress = false;
  48.         //...calculate working time
  49.         return showProgress;
  50.     }
  51.     private void progressTaskCompleted()
  52.     {//not step here with _scheduler
  53.  
  54.         //Show and Hide IPopup window
  55.     }
  56. }
  57.        
  58. public Task CreateTask(Action action, TaskScheduler scheduler)
  59. {
  60.     // I'm assuming progressTaskStarted does UI stuff to show progress,
  61.     // and progressTaskCompleted hides it when the work is done.
  62.  
  63.     return Task.Factory.StartNew(progressTaskStarted)
  64.         .ContinueWith(ignoredTask => action(), TaskCreationOptions.LongRunning)
  65.         .ContinueWith(ignoredTask => progressTaskCompleted());
  66. }
clone this paste RAW Paste Data