Reputation: 7028
I am new to async / await. but I created the POC but I am still confused.
Outcome of method
public async void WriteLineFunc(string str)
{
await Task.Factory.StartNew(() => WaitFor2Secs());
//WaitFor2Secs();
Console.WriteLine(str);
}
and
public async void WriteLineFunc(string str)
{
//await Task.Factory.StartNew(() => WaitFor2Secs());
WaitFor2Secs();
Console.WriteLine(str);
}
is same. What is point of making a method as await? Just to run a function on other thread and wait for its completion?
Upvotes: 0
Views: 332
Reputation: 456497
When a method uses await
, it can return to its caller before it's complete.
Consider this example:
public async Task WriteLineFuncAsync(string str)
{
await Task.Delay(2000);
Console.WriteLine(str);
}
public void WriteLineFunc(string str)
{
Thread.Sleep(2000);
Console.WriteLine(str);
}
WriteLineFunc
will synchronously block the running thread for 2 seconds and then write out the string. WriteLineFuncAsync
will immediately return an incomplete Task
to its caller; two seconds later, it will write out the string and then complete the Task
.
For client-side applications, the main benefit is responsiveness (the GUI thread is not blocked). For server-side applications, the main benefit is scalability (you can have far more responses than threads).
Upvotes: 7