Is it possible to call an awaitable method in a non async method?

Thomas Salandre picture Thomas Salandre · Sep 13, 2012 · Viewed 33.7k times · Source

In a windows 8 application in C#/XAML, I sometimes want to call an awaitable method from a non asynchronous method.

Actually is it correct to replace this :

  public async Task<string> MyCallingMethod()
  {
      string result = await myMethodAsync();
      return result;
  }

by this :

   public string MyCallingMethod()
   {
       Task.Run(async () => {
            string result = await myMethodAsync();
            return result;
             });
   }

The advantage for me is that I can use MyCallingMethod without await but is this correct? This can be an advantage if I want to pass a ref parameter for MyCallingMethod since It is not possible to have ref parameters in an async method.

Answer

Martin Suchan picture Martin Suchan · Sep 13, 2012

In non-async method you can either start the Task asynchronously and not wait for the result:

public void MyCallingMethod()
{
    Task t = myMethodAsync();
}

or you can attach ContinueWith event handler, which is called after finishing the Task,

public void MyCallingMethod()
{
    myMethodAsync().ContinueWith(
        result =>
        {
            // do stuff with the result
        });
}

or you can get the result from the Task synchronously:

public string MyCallingMethod()
{
    string result = myMethodAsync().Result;
    return result;
}