title: C# async aggregate and dispatch
body: <p>I'm having trouble assimilating the c# Task, async and await patterns. </p>
  
  <p>Windows service, .NET v4.5.2 server-side.</p>
  
  <p>I have a Windows service accepting a variety of sources of incoming records, arriving externally ad-hoc via a self-hosted web api. I would like to batch up these records and then forward them on to another service. If the number of batched records exceeds a threshold, the batch should be dispatched immediately. Furthermore, the batch as it stands should also be dispatched if a time interval has elapsed. This means that a record is never held for more than <em>N</em> seconds. </p>
  
  <p>I'm struggling to fit this into a Task based async pattern.</p>
  
  <p>In days gone by, I would have created a Thread, a ManualResetEvent and a System.Threading.Timer. The Thread would loop around a Wait on the reset event. The Timer would set the event when fired, as would the code doing the aggregation when the batch size exceeded the threshold. Following the Wait, the Thread would stop the Timer, do the dispatch (an HTTP Post), reset the Timer and clear the ManualResetEvent, the loop back and Wait.</p>
  
  <p>However, I am seeing folk say that this is 'bad' as the Wait just blocks a valuable thread resource, and that async/await is my panacea.</p>
  
  <p>First off, are they right? Is my way out-of-date and inefficient or can I JFDI?</p>
  
  <p>I've found examples <a href="https://stackoverflow.com/questions/24055900/how-to-aggregate-the-data-from-an-async-producer-and-write-it-to-a-file">here</a> for batching and <a href="https://stackoverflow.com/questions/4890915/is-there-a-task-based-replacement-for-system-threading-timer">here</a> for tasks at intervals, but not a combination of the two. </p>
  
  <p>Is this requirement actually compatible with async/await?</p>