Zain Rizvi
Zain Rizvi

Reputation: 24656

Is it better to call async or synchronous versions of a method from a synchronous Task?

If I'm running code in a synchronous Task, is it better to call the async version of the method and wait for the result or just call the synchronous version of the code?

That is, will I use less resources if I create a new task using myMethod1 or myMethod2?

public void SomeFunc() {
  // Wrapper code
  Task myTask = new Task(myMethod1);
  myTask.Run();
  // Do stuff
  myTask.Wait();
}

private void myMethod1() {
  CloudQueueMessage message = myCloudQueue.GetMessage();
  // do stuff
}

private void myMethod2() {
  CloudQueueMessage message = myCloudQueue.GetMessageAsync().Result;
  // do stuff
}

I'm wondering if using the async version somehow makes the thread available on the threadpool again while the async operation is running.

Upvotes: 1

Views: 97

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564851

I'm wondering if using the async version somehow makes the thread available on the threadpool again while the async operation is running.

That would only work if you were doing this asynchronously. Since you're calling .Result on the task, you block the thread while waiting. As such, there's zero benefit in using the asynchronous version in that code.

If this is the entire goal, it would be much better to write:

public async Task SomeFunc() {
  // Wrapper code
  Task myTask = MyMethod1;
  // Do stuff
  await myTask;
}

private async Task myMethod1() {
   CloudQueueMessage message = await myCloudQueue.GetMessageAsync();
   // do stuff
}

This keeps everything asynchronous, including your Task.

Upvotes: 2

Related Questions