title: How to create and use a custom Awaitable in c#?
body: <p>I'm trying to implement a custom awaiteable to execute <code>await Thread.SleepAsync()</code> without creating any additional threads.</p>
  
  <p>Here's what I've got:</p>
  
  <pre><code>    class AwaitableThread : INotifyCompletion
      {
          public AwaitableThread(long milliseconds)
          {
              var timer = new Timer(obj =&gt; { IsCompleted = true; }, null, milliseconds, Timeout.Infinite);
          }
  
          private bool isCompleted = false;
  
          public bool IsCompleted
          {
              get { return isCompleted; }
              set { isCompleted = value; }
          }
  
          public void GetResult()
          {}
  
          public AwaitableThread GetAwaiter() { return this; }
  
          public void OnCompleted(Action continuation)
          {
              if (continuation != null)
              {
                  continuation();
              }
          }
      }
  </code></pre>
  
  <p>And here's how the sleep would work:</p>
  
  <pre><code>    static async Task Sleep(int milliseconds)
      {
          await new AwaitableThread(milliseconds);
      }
  </code></pre>
  
  <p>The problem is that this function returns immidiatly, even though in <code>OnCompleted</code>, <code>IsCompleted</code> is still false.</p>
  
  <p>What am I doing wrong?</p>