Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run async task without need to await for result in current function/thread?

Is there any chance to avoid waiting? What we want for example:

async Task SomeTask()  
{  
   await ChildTask();

   //Then something we want to be done without waiting till "Child Task" finished  
   OtherWork();  
}  

async Task ChildTask()  
{  
   //some hard work   
}  
like image 289
Timurid Avatar asked Mar 21 '15 20:03

Timurid


People also ask

Can I call an async method without await?

However, just to address "Call an async method in C# without await", you can execute the async method inside a Task. Run . This approach will wait until MyAsyncMethod finish. await asynchronously unwraps the Result of your task, whereas just using Result would block until the task had completed.

Does async await run on separate thread?

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. The async and await keywords don't cause additional threads to be created.

What happens if we execute an asynchronous method but do not await it?

If you forget to use await while calling an async function, the function starts executing. This means that await is not required for executing the function. The async function will return a promise, which you can use later.

Do async functions run on another thread?

Async programming is about non-blocking execution between functions, and we can apply async with single-threaded or multithreaded programming. So, multithreading is one form of asynchronous programming.


2 Answers

Capture the Task and then await it after OtherWork is done:

async Task SomeTask()  
{  
   var childTask = ChildTask();

   //Then something we want to be done without waiting till "Child Task" finished  
   OtherWork();  
   await childTask;
}  
like image 83
John Koerner Avatar answered Sep 22 '22 07:09

John Koerner


You're not forced to await an asynchronous Task. If you don't await it, it's because you don't care if it finishes successfully or not (fire and forget approach).

If you do so, you shouldn't use the async keyword in your method/delegate signatures.

like image 43
Matías Fidemraizer Avatar answered Sep 22 '22 07:09

Matías Fidemraizer