title: Read and write same memory from different threads
body: <p>I have a simple class which sends requests asynchronously.</p>
  
  <pre><code>public class MyClass
  {
      private readonly ISender _sender;
  
      public MyClass(ISender sender)
      {
          _sender = sender;
      }
  
      public Task&lt;string&gt; SendAsync(string input, CancellationToken cancellationToken)
      {
          return _sender.SendAsync(input, cancellationToken);
      }
  }
  
  public interface ISender
  {
      Task&lt;string&gt; SendAsync(string input, CancellationToken cancellationToken);
  }
  </code></pre>
  
  <p>All looks simple, until the following requirement: _sender can be changed at runtime.</p>
  
  <p>New implementation of MyClass: </p>
  
  <pre><code>public class MyClass
  {
      private readonly ISender _sender;
  
      public MyClass(ISender sender)
      {
          _sender = sender;
      }
  
      public Task&lt;string&gt; SendAsync(string input, CancellationToken cancellationToken)
      {
          return _sender.SendAsync(input, cancellationToken);
      }
  
      public void SenderChanged(object unused, SenderEventArgs e)
      {
          ISender previous = Interlocked.Exchange(ref _sender, SenderFactory.Create(e.NewSenderConfig));
          previous.Dispose();
      }
  }
  </code></pre>
  
  <p>Obviously this code is not thread-safe. I would need to introduce <code>lock</code> in both <code>SendAsync</code> and <code>SenderChanged</code> to make sure that _sender is always the up-to-date object. 
  But I expect the <code>SenderChanged</code> to be called once per day let's say, and <code>SendAsync</code> (reading the _sender object) to be called 10000/second.<br>
  <code>Lock</code> and context switching would kill the performance of this code.</p>
  
  <p>Is there a possible way to handle this with low level locking? Or how would you solve this problem knowing the above requirement? </p>