title: Is it needed to make fields thread-safe when using async/await?
body: <p>Sometimes I encounter async/await code that accesses fields of an object. For example this <a href="https://github.com/dotnet-state-machine/stateless/blob/dev/src/Stateless/StateMachine.Async.cs#L135" rel="nofollow noreferrer">snippet</a> of code from the Stateless project:</p>
  
  <pre><code>private readonly Queue&lt;QueuedTrigger&gt; _eventQueue = new Queue&lt;QueuedTrigger&gt;();
  private bool _firing;
  
  async Task InternalFireQueuedAsync(TTrigger trigger, params object[] args)
  {
      if (_firing)
      {
          _eventQueue.Enqueue(new QueuedTrigger { Trigger = trigger, Args = args });
          return;
      }
  
      try
      {
          _firing = true;
  
          await InternalFireOneAsync(trigger, args).ConfigureAwait(false);
  
          while (_eventQueue.Count != 0)
          {
              var queuedEvent = _eventQueue.Dequeue();
              await InternalFireOneAsync(queuedEvent.Trigger, queuedEvent.Args).ConfigureAwait(false);
          }
      }
      finally
      {
          _firing = false;
      }
  }
  </code></pre>
  
  <p>If I understand correctly the <code>await **.ConfigureAwait(false)</code> indicates that the code that is executed after this <code>await</code> does <a href="https://blog.stephencleary.com/2012/02/async-and-await.html" rel="nofollow noreferrer">not necessarily</a> has to be executed on the same context. So the <code>while</code> loop here could be executed on a ThreadPool thread. I don't see what is making sure that the <code>_firing</code> and <code>_eventQueue</code> fields are synchronized, for example what is creating the a lock/memory-fence/barrier here? So my question is; do I need to make the fields thread-safe, or is something in the async/await structure taking care of this?</p>
  
  <p>Edit: to clarify my question; in this case <code>InternalFireQueuedAsync</code> should always be called on the same thread. In that case only the continuation could run on a different thread, which makes me wonder, do I need synchronization-mechanisms(like an explicit barrier) to make sure the values are synchronized to avoid the issue described here: <a href="http://www.albahari.com/threading/part4.aspx" rel="nofollow noreferrer">http://www.albahari.com/threading/part4.aspx</a></p>
  
  <p>Edit 2: there is also a small discussion at stateless:
  <a href="https://github.com/dotnet-state-machine/stateless/issues/294" rel="nofollow noreferrer">https://github.com/dotnet-state-machine/stateless/issues/294</a></p>