Waleed Naveed
Waleed Naveed

Reputation: 2381

Async method not returning control back to caller method

I have the following code

class Program
{
    public  async  Task<bool> StartMyTask()
    {
        await Foo();

        return true;

    }

    public async Task<bool> Foo()
    {

        for (int i = 0; i < 1000000; i++)
        {
            Console.WriteLine("Loop");
        }
        return true;

    }


    static void Main(string[] args)
    {
        Program obj = new Program();

        var myTask = obj.StartMyTask();     
        Console.WriteLine("Before Task Return");                                    


        Console.ReadLine();
    }
}

According to my understanding when "await Foo()" gets called, a thread will be created which will execute the "Foo()" method and the control would be returned back to the caller (Main method).

By considering this, "Before Task Return" should be printed before the "Foo()" method completes. But its not happening, first the "Foo()" method completes and then "Before Task Return" is displayed.

Upvotes: 0

Views: 1889

Answers (2)

Stephen Cleary
Stephen Cleary

Reputation: 457422

According to my understanding when "await Foo()" gets called, a thread will be created which will execute the "Foo()" method and the control would be returned back to the caller (Main method).

No, absolutely not. async and await do not create threads on their own. async allows you to use await, and await will "asynchronously wait" - i.e., pause the method, return, and then resume the method when its operation completes.

Note that the compiler is giving you a warning that you have a method marked async but it will run synchronously. So the compiler is already telling you exactly what's wrong.

If you want to use a background thread, you can use Task.Run to call the synchronous Foo method:

public async Task<bool> StartMyTask()
{
  await Task.Run(() => Foo());
  return true;
}

public bool Foo()
{
  for (int i = 0; i < 1000000; i++)
  {
    Console.WriteLine("Loop");
  }
  return true;
}

Upvotes: 6

muaz
muaz

Reputation: 609

Since your Foo method creates no task then your code wont diverge as you expect, but making it as follows resolves your concerns:

public async Task<bool> Foo()
    {
       return await Task.Run(() =>
       {
           for (int i = 0; i < 100000; i++)
           {
               Console.WriteLine("Loop");
           }
           return true;
       });
    }

Upvotes: -1

Related Questions