title: How to disallow Task from being interrupted by await?
body: <p>Coming from JavaScript I am used to the fact that code execution does not interleave, with await expressions being an exception, which define fixed re-entry points.<br>
  The .NET asynchrony semantics appear to be different though: During every call of <code>Thread.Sleep</code>, a <code>Task</code> waiting to be run jumps in and performs work. Then, <strong>on return of of the <code>Sleep</code> call, the <code>Task</code>'s computation is interrupted immediately</strong>, as the code below demonstrates.</p>
  
  <p>How can I achieve atomic execution of the loop? (Without locks or the like; assuming a single thread)</p>
  
  <pre><code>static async Task RunExperiment()
  {
      var task = DoNotInterruptMe();
      Console.WriteLine("sleep...");
      Thread.Sleep(60);
      Console.WriteLine("sleep...");
      Thread.Sleep(60);
      Console.WriteLine($"Interrupted, because i={i}");
      Console.WriteLine("sleep...");
      Thread.Sleep(100);
      Console.WriteLine($"Interrupted again, because i={i}");
      await task;
      Console.WriteLine("task.Status: "+task.Status);
  }
  
  private static int i;
  
  static async Task DoNotInterruptMe()
  {
      Console.WriteLine("I: delay...");
      await Task.Delay(100);
      Console.WriteLine("I: working...");
      int j = 1;
      for (i = 0; i &lt; 1&lt;&lt;30; i++)
      {
          j *= i;
      }
      Console.WriteLine("I: finished work");
  }
  </code></pre>
  
  <p>Run above using</p>
  
  <pre><code>RunExperiment().Wait();
  </code></pre>
  
  <p>I am using <code>Thread.Sleep</code> here, but <code>await Task.Delay(60)</code> behaves just alike.</p>
  
  <h3>Sample output:</h3>
  
  <pre><code>I: delay...
  sleep...
  sleep...
  I: working...
  Interrupted, because i=358449
  sleep...
  Interrupted again, because i=8598631
  I: finished work
  task.Status: RanToCompletion
  </code></pre>