Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between await and Task.Wait [duplicate]

Tags:

c#

First way:

var tds=SearchProcess();
await tds;

public async  Task<XmlElement> SearchProcess()
{
}

Second way:

var tds= Task.Factory.StartNew(()=>SearchProcess());
Task.WaitAll(tds);

public XmlElement SearchProcess()
{
}

In above both approach any performance difference is there?

like image 473
dsaralaya Avatar asked Dec 27 '13 12:12

dsaralaya


People also ask

Is task wait the same as await?

Wait and await - while similar conceptually - are actually completely different. Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. As a general rule, you should use " async all the way down"; that is, don't block on async code.

What is the difference between task and async await?

Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.

What is task wait?

Wait is a synchronization method that causes the calling thread to wait until the current task has completed. If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread.

What is the difference between wait and await C#?

'Wait' means to pass the time until an anticipated event occurs, whereas 'await' means to wait for something with a hope.


1 Answers

Task.WaitAll is blocking, while using await will make the containing method async. To wait for multiple tasks asynchronously you can use Task.WhenAll:

public async Task DoSomething()
{
    IEnumerable<Task> tds = SearchProcess();
    await Task.WhenAll(tds);
    //continue processing    
}
like image 196
Lee Avatar answered Oct 02 '22 02:10

Lee