Hi All,
I am a little confused between Task vs Async in C#, can anyone explain what exact difference between when to use where, I have seen some places both in the same method.
Hi All,
I am a little confused between Task vs Async in C#, can anyone explain what exact difference between when to use where, I have seen some places both in the same method.
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Sam HobbsPosted Feb 18, 2022, 12:03 AM
In the past I have searched for async and await. I have found few simple explanations, most of what I find just confuses me more. The one simple explanation that I think helps is that async and await do not create tasks, so it does not help to compare async and await to the Task class. If you are unfamiliar with multitasking (such as the Task class) then it might help to learn how to use the Thread class with the AutoResetEvent Class and related classes. Look at the samples in that page. Most Microsoft samples will use async and await but it might help to learn how to use the Task or Thread class the other way too.
Rajesh GamiPosted Feb 11, 2022, 10:08 AM
When using async and await the compiler generates a state machine in the background.
Here's an example on which I hope I can explain some of the high-level details that are going on:
longRunningTask = LongRunningOperationAsync();
LongRunningOperationAsync() // assume we return an int from this long running operation longRunningTask = LongRunningOperationAsync(); starts executing LongRunningOperation
public async Task MyMethodAsync()
{
Task
// independent work which doesn't need the result of LongRunningOperationAsync can be done here
//and now we call await on the task
int result = await longRunningTask;
//use the result
Console.WriteLine(result);
}
public async Task
{
await Task.Delay(1000); // 1 second delay
return 1;
}
OK, so what happens here:
1.) Task
2). Independent work is done on let's assume the Main Thread (Thread ID = 1) then await longRunningTask is reached.
Now, if the longRunningTask hasn't finished and it is still running, MyMethodAsync() will return to its calling method, thus the main thread doesn't get blocked. When the longRunningTask is done then a thread from the ThreadPool (can be any thread) will return to MyMethodAsync() in its previous context and continue execution (in this case printing the result to the console).
A second case would be that the longRunningTask has already finished its execution and the result is available. When reaching the await longRunningTask we already have the result so the code will continue executing on the very same thread. (in this case printing result to console). Of course this is not the case for the above example, where there's a Task.Delay(1000) involved.
Vicente Gerardo Guzman LucioPosted Feb 10, 2022, 10:55 PM
async is an indicator to the compiler that the method contains an await.
When this is the case, your method implicitly returns a Task, so you don't need to...
Muhammad Imran AnsariPosted Jan 31, 2022, 5:17 AM
To enhance performance and overall responsiveness, C# 5 introduced a simplified style, async programming, that influences asynchronous support in the .NET Framework 4.5 and higher. Asynchronous programming is normally very helpful when we are working with such blocking activities or whereas should wait for sometimes like File handling, Image processing, web access (sometimes is slow or delayed) and ports communications.
Ultimately purpose of using this paradigm is improves responsiveness.
public async Task FunctionAsync() getStringTask = client.GetStringAsync("webURL");
{
var client = new HttpClient();
Task
await Task.Delay(100);
}
Above method contains the word async. This keyword allows for the word await to be used inside the method. The method (FunctionAsync) runs synchronously until it finds the word await and that await word is the one that takes care of asynchrony. await is an operator that receives a parameter, and an awaitable (an asynchronous operation).
Finally, the async method is on pause until the awaitable is complete (wait), but the thread is not blocked by this call (it is asynchronous).
Sachin SinghPosted Jan 30, 2022, 1:06 PM
Now, why Task, async and await?
See, the methods are executed in the order they appears in a program. let's take an example
public void InsertEmployee(List emps) // 5M records
{
Console.WriteLine("enter your name");
AddToDB(emps); // taking 2 minutes
Console.WriteLine("How was your day");// will not execute untill records ends.
}
// Your business/DAL method
public void AddToDb(List emps)
{
// insert into database
}
so, untill AddToDB() method completely finishes its job, the next line won't execute and the UI will be blocked.
so, we declare the method as Task , and use async and await.
Async and Await acts as code markers and frees the Main thread so that the next line could execute.
public Task AddToDb(List emps)
{
// insert into database
}
public async Task InsertEmployee(List emps)
{
Console.WriteLine("enter your name");
await AddToDB(emps); // notice here
Console.WriteLine("How was your day");
How does async and await actually works and why not simply start a new thread using Thread.Start(()=>AddToDb())
Multi-threading is actually not parallel, because instead of utilizing the cores (CPU's in your PC) in parallel efficiently, they run on a single core and do time slicing, means exeutes one method for some time then switch to other method and gives us a sense of parallel execution but in reality uses just one Core even if you have multi-core PC.
2. TPL (Task parallel library) does the work really in parallel and utilizes all the cores efficiently.
3. Async just introduces a state machine and now the method actually becomes object and properties.
4. Await frees the calling thread and acts as a checkpoint for the state machine that tells from where to resume the method when others get completed.