title: How to aggregate the data from an async producer and write it to a file?
body: <p>I'm learning about async/await patterns in C#. Currently I'm trying to solve a problem like this:</p>
  
  <ul>
  <li><p>There is a producer (a hardware device) that generates 1000 packets per second. I need to log this data to a file. </p></li>
  <li><p>The device only has a <code>ReadAsync()</code> method to report a single packet at a time.</p></li>
  <li><p>I need to buffer the packets and write them in the order they are generated to the file, only once a second.</p></li>
  <li><p>Write operation should fail if the write process is not finished in time when the next batch of packets is ready to be written.</p></li>
  </ul>
  
  <p>So far I have written something like below. It works but I am not sure if this is the best way to solve the problem. Any comments or suggestion? What is the best practice to approach this kind of Producer/Consumer problem where the consumer needs to aggregate the data received from the producer?</p>
  
  <pre><code>static async Task TestLogger(Device device, int seconds)
  {
      const int bufLength = 1000;
      bool firstIteration = true;
      Task writerTask = null;
  
      using (var writer = new StreamWriter("test.log")))
      {
          do
          {
              var buffer = new byte[bufLength][];
  
              for (int i = 0; i &lt; bufLength; i++)
              {
                  buffer[i] = await device.ReadAsync();
              }
  
              if (!firstIteration)
              {
                  if (!writerTask.IsCompleted)
                      throw new Exception("Write Time Out!");
              }
  
              writerTask = Task.Run(() =&gt;
                  {
                      foreach (var b in buffer)
                          writer.WriteLine(ToHexString(b));
                  });
  
              firstIteration = false;
          } while (--seconds &gt; 0);
      }
  }
  </code></pre>