Keithin8a
Keithin8a

Reputation: 961

Task.wait vs async await

I have been looking into upgrading the way that we do async tasks in our software. For years the software has been running in .net 2.5 and the team previous, decided to implement their own async task architecture which for the most part is OK but difficult to use for more complicated things.

I was watching a tutorial which explained tasks in C# really well but then started looking at async methods and the await keyword to keep the software up to date. My question is, why you would want to use async and await over just creating a task and using .wait/.waitAll/.waitAny.

I have read things that say that it isn't creating new threads (which suggests its not as parallel) and that it has a performance overhead.

Can you still apply the wait all one by one methodology? I am guessing since the async returns a task you would just use this to populate your list but that just furthers my argument on why would you bother using it?

Upvotes: 0

Views: 1394

Answers (1)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149518

My question is, why you would want to use async and await over just creating a task and using .wait/.waitAll/.waitAny.

A task is merely a promise of your which will complete in the future. Task != Thread , and that is an important thing to remember.

I have read things that say that it isn't creating new threads (which suggests its not as parallel) and that it has a performance overhead.

That depends on how the Task is being created.

For example:

public async Task<string> GetPageAsync(string url)
{
    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(url);
    return response.Content.ReadAsStringAsync();
}

This operations generates no threads, but still returns a Task<string>. using async-await has some overhead because under the covers, the compiler creates a state-machine which manages the execution flow, which has to take care of many things.

While this:

return Task.Run(FooOperation);

Requests a thread pool thread to run FooOperation on.

A task can be generated for doing overlapped IO (like the first example) operations which require no thread at all. When you create a task and use Wait/WaitAll/WaitAny, you're blocking on the call, and then you end up asking yourself why use that at all and not run it synchronously instead?

For async-await, you can use the asynchronous WhenAny/WhenAll, which themselfs yield an awaitable which can be asynchronously waited.

Upvotes: 2

Related Questions