title: How to cancel a TaskCompletionSource using a timeout
body: <p>I have the function that I call asynchronously using the await keyword:</p>
  <pre><code>public Task&lt;StatePropertyEx&gt; RequestStateForEntity(EntityKey entity, string propName)
  {
      var tcs = new TaskCompletionSource&lt;StateInfo&gt;();
      try
      {
          var propInstance = BuildCacheKey(entity, propName);
          StateCacheItem cacheItem;
          if (_stateCache.TryGetValue(propInstance, out cacheItem))
          {
              tcs.SetResult( new StateInfo (cacheItem.State.Name, cacheItem.State.Value) );
              return tcs.Task;
          }
  
          //state not found in local cache so save the tcs for later and request the state
          var cacheKey = BuildCacheKey(entity, propName);
         _stateRequestItemList.TryAdd(cacheKey, new StateRequestItem(entity, propName, tcs));
  
          _evtClient.SubmitStateRequest(entity, propName);
  
          return tcs.Task;
      }
      catch (Exception ex)
      {
          tcs.SetException(ex);
          return tcs.Task;
      }
  }
  </code></pre>
  <p>The function has a look to see if it has the information it needs and if it does it returns it. If it doesn’t have the details it sends a request out which should eventually come in as an event. At that point my code (not shown) finds the stored TaskCompletionSource item, sets the result and returns it. This all works fine but I have now been asked to consider a situation where a reply may never be returned when I request state via the “_evtClient.SubmitStateRequest(entity, propName);” line. I need to implement some sort of timeout mechanism so I can cancel the TCS task so the function caller can fail gracefully. I’ve been looking on SO and the internet and can’t find anything that looks right. I’m now not sure if I need to restructure the above code in a different way. Can anyone advise or point me to a similar scenario?</p>
  <p>The code that calls the above function can call it in a single hit like this:</p>
  <pre><code>var stateProperty = await RequestStateForEntity(key, stateName);
  </code></pre>
  <p>or in a batch, like this:</p>
  <pre><code>await
      Task.WhenAll(
          stateDefinitions.Select(stateDefinition =&gt; stateDefinition.Name)
              .Select(
                  stateName =&gt;
                      Task.Factory.StartNew(
                          async () =&gt; results.Add(await RequestStateForEntity(key, stateName)))
                          .Unwrap())
              .ToArray());
  </code></pre>