CCR tips and tricks - part 16

The pattern used in part 15 can be implemented as a helper method that looks like this:

   1: public static void ExecuteUsingClrThreadPool(Action handler)
  2: {
  3:     if (handler == null)
  4:     {
  5:         throw new ArgumentNullException("handler");
  6:     }
  7:  
  8:     if (Thread.CurrentThread.IsThreadPoolThread)
  9:     {
 10:         handler();
 11:     }
 12:     else
 13:     {
 14:         using (var dispatcherQueueUsingClrThreadPool = new DispatcherQueue())
 15:         {
 16:             Arbiter.ExecuteToCompletion(
 17:                 dispatcherQueueUsingClrThreadPool, 
 18:                 Arbiter.FromHandler(() => handler()));
 19:         }
 20:     }
 21: }

Using that helper the method from part 15 can be implemented like this:

  22: private IEnumerator<ITask> MethodThatNeedToCallBlockingMethodFromCcr(
 23:     DispatcherQueue taskQueue,
 24:     Port<EmptyValue> donePort)
 25: {
 26:     yield return
 27:         Arbiter.ExecuteToCompletion(
 28:             taskQueue, 
 29:             Arbiter.FromHandler(
 30:                 () => ExecuteUsingClrThreadPool(
 31:                     () => this.BlockingMethod(42))));
 32:     donePort.Post(EmptyValue.SharedInstance);
 33: }