title: Lazy single-threaded worker
body: <p>I have a thread that reads data in small chunks and puts it into <code>ImmutableList&lt;T&gt;</code>. I need to dump this list into a file. Originally I was dumping the list on every update but with time list grew and file size is now close to 200Mb so writing file takes too much time to keep it synchronous.
  I've made file writing asynchronous and the code I currently have is:</p>
  
  <pre><code>public ImmutableList&lt;T&gt; Items { get; private set; }
  
  public void Insert(IEnumerable&lt;T&gt; items)
  {
      lock (_syncObj)
      {
          Items = Items.AddRange(items).Sort(_sortOrder);
          QueueSaving();
      }
  }
  
  void SavingThread()
  {
      for (; ; )
      {
          var snapshot = Items;
          SaveItems(snapshot);
  
          lock (_syncObj)
          {
              if (snapshot == Items)
                  Monitor.Wait(_syncObj);
          }
      }
  }
  
  void QueueSaving()
  {
      lock (_syncObj)
          Monitor.Pulse(_syncObj);
  }
  </code></pre>
  
  <p>I.e. if there were many updates since the last write then writer just saves the last version.
  Obviously I now have to have a thread that is dedicated to saving and which sleeps when there are no updates.</p>
  
  <p>What would be the cleanest code to avoid having a dedicated writer thread? I.e. run QueueSaving until file writer caught up with the list changes and finish, then start it on the next change?</p>