title: Using Task.WhenAny() in a web service
body: <p>I have a web service that needs to return data as fast as possible. I have two sources that I can query. I want to return use <code>Task.WhenAny()</code> to query these sources and return the item which returns first. When I run my code on my local dev environment, the code will successfully return data from the fastest task BUT when the slower task returns, it crashes my IIS Express Worker Process with a null reference exception. </p>
  
  <p>MyService.asmx</p>
  
  <pre><code>&lt;%@ WebService Language="C#" CodeBehind="MyService.asmx.cs" Class="MyWebService.MyService" %&gt;
  </code></pre>
  
  <p>MyService.asmx.cs</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.Services;
  
  namespace MyWebService
  {
      /// &lt;summary&gt;
      /// Summary description for Service1
      /// &lt;/summary&gt;
      [WebService(Namespace = "http://tempuri.org/")]
      [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
      [System.ComponentModel.ToolboxItem(false)]
      // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
      // [System.Web.Script.Services.ScriptService]
      public class MyService : System.Web.Services.WebService
      {
          private WebCore _webService;
  
          public MyService()
          {
              _webService = new WebCore();
          }
  
  
          [WebMethod]
          public int TestAsync()
          {
              return _webService.TestInt();
          }
  
      }
  }
  </code></pre>
  
  <p>WebCore.cs</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Threading;
  using System.Threading.Tasks;
  
  namespace MyWebService
  {
     public class WebCore {
  
         public WebCore() {}
  
          public int TestInt()
          {
              return AsyncCaller().Result;
          }
          private CancellationTokenSource cts;
  
          async Task&lt;int&gt; CallOne(CancellationToken ct)
          {
              await Task.Delay(4000);
              return 1;
          }
          async Task&lt;int&gt; CallTwo(CancellationToken ct)
          {
              await Task.Delay(1000);
              return 2;
          }
          private async Task&lt;int&gt; AsyncCaller()
          {
              cts = new CancellationTokenSource();
              var tasks = new List&lt;Task&lt;int&gt;&gt;()
              {
                  CallOne(cts.Token),
                  CallTwo(cts.Token)
              };
  
              var completedtasks = await Task.WhenAny(tasks);
              var res = await completedtasks;
              cts.Cancel();
              return res;
          }
     }
  }
  </code></pre>
  
  <p>When I execute this in debug mode and run my web service, the web service will return "2" as expected. However 3 seconds later when CallOne() completes, my app crashes with "The call stack contains only external code" with null reference exception "bject reference not set to an instance of an object". My  My stack trace is:</p>
  
  <pre><code> at System.Web.ThreadContext.AssociateWithCurrentThread(Boolean setImpersonationContext)
     at System.Web.HttpApplication.OnThreadEnterPrivate(Boolean setImpersonationContext)
     at System.Web.LegacyAspNetSynchronizationContext.CallCallbackPossiblyUnderLock(SendOrPostCallback callback, Object state)
     at System.Web.LegacyAspNetSynchronizationContext.CallCallback(SendOrPostCallback callback, Object state)
     at System.Web.LegacyAspNetSynchronizationContext.Post(SendOrPostCallback callback, Object state)
     at System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.PostAction(Object state)
     at System.Threading.Tasks.AwaitTaskContinuation.RunCallback(ContextCallback callback, Object state, Task&amp; currentTask)
  --- End of stack trace from previous location where exception was thrown ---
     at System.Threading.Tasks.AwaitTaskContinuation.&lt;ThrowAsyncIfNecessary&gt;b__1(Object s)
     at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
     at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
     at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
     at System.Threading.ThreadPoolWorkQueue.Dispatch()
     at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
  </code></pre>