femtoRgon
femtoRgon

Reputation: 33341

Why use Task.Run to create a new task around a simple async method call?

This is a pattern I'm seeing in some code I'm working on:

result = await Task.Run(async () => await MyAsynchronousMethod());

and I'm failing to see what this does that this does not do:

result = await MyAsynchronousMethod();

What is the former construction here intended to accomplish?

Upvotes: 2

Views: 103

Answers (1)

mm8
mm8

Reputation: 169270

Task.Run starts a task on the thread pool that will execute the async method. So in the first case, the async method itself will be called on a background thread.

In the second case, the MyAsynchronousMethod method will run synchronously, just like any other non-async method, on the calling thread until it hits an await. This might block the calling thread, at least for a while, depending on how the async method is implemented.

There are examples of poorly implemented async methods that blocks the calling thread before they hit an await and calling such a method on the dispatcher thread in a UI application may for example freeze the application.

Upvotes: 3

Related Questions