title: TaskCompletionSource in async function
body: <p>I have such a function:</p>
  
  <pre><code>public async Task&lt;bool&gt; DoSomething()
  {
     var tcs = new TaskCompletionSource&lt;bool&gt;();
  
     // Here is the problem. I need to keep this line because I wait on something asynchronously, but the function must return bool and I can't just return tcs.Task
     while(something)
        await Task.Delay(100);
  
     someobject.somevent += () =&gt; {
        // do some sht
        tcs.SetResult(true);
     }
  
     // it doesn't work
     return tcs.Task;
  }
  </code></pre>
  
  <p>It's just a fake code but I have real situation where I need this. I want to keep DoSomething asynchronous but I also want to keep Task.Delay/Sleep in it. How do I do this in not-async function returning just Task?</p>
  
  <p>UPDATE:</p>
  
  <p>THIS WORKS:</p>
  
  <pre><code>class Program
      {
          static TaskCompletionSource&lt;bool&gt; tcs = new TaskCompletionSource&lt;bool&gt;();
  
  
          static Task&lt;bool&gt; Test()
          {
             // tcs = new TaskCompletionSource&lt;bool&gt;();
              Task.Factory.StartNew(() =&gt;
              {
                  Console.WriteLine("Waiting...");
                  Thread.Sleep(5000);
                  Console.WriteLine("Setting result");
                  if(tcs.TrySetResult(true))
                      Console.WriteLine("Result has been set");
  
  
              });
  
              return tcs.Task;
          }
  
          static async Task Test2()
          {
              Console.WriteLine("Starting awaiting");
              var result = await Test();
              Console.WriteLine(result.ToString());
          }
  
          static void Main(string[] args)
          {
  
  
              Test2();
  
              Console.ReadKey(false);
  
          }
      }
  </code></pre>
  
  <p>and this doesn't</p>
  
  <pre><code>static async Task&lt;bool&gt; Test()
  {
     // tcs = new TaskCompletionSource&lt;bool&gt;();
      Task.Factory.StartNew(() =&gt;
      {
          Console.WriteLine("Waiting...");
          Thread.Sleep(5000);
          Console.WriteLine("Setting result");
          if(tcs.TrySetResult(true))
              Console.WriteLine("Result has been set");
  
  
      });
  
  
      return await tcs.Task;
  }
  </code></pre>
  
  <p>what's worse, I have tested it in my windows forms app and awaiting tcs.Task caused weird crash coming from System.Threading....dll</p>