Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# How to start an async method without await its complete?

Sometimes I need to start an async job which works very slow. I don't care if that job success and I need to continue working on my current thread.

Like sometimes I need to send an Email or SMS which works very slow. I need to respond to the web client as soon as possible so I don't want to await it.

I have googled this question and some articles suggest me to write like this:

// This method has to be async public async Task<Response> SomeHTTPAction() {     // Some logic...     // ...      // Send an Email but don't care if it successfully sent.     Task.Run(() =>  _emailService.SendEmailAsync());     return MyRespond(); } 

Or like this:

// This method has to be async public async Task<Response> SomeHTTPAction() {     // Some logic...     // ...      // Send an Email but don't care if it successfully sent.     Task.Factory.StartNew(() =>  _emailService.SendEmailAsync());     return MyRespond(); } 

There will be a warning says: before the call is completed. Consider applying the 'await' operator to the result of the call.

So what if I really awaited it? What is the best practice in C# to 'fire and forget', just call an async method without waiting for its complete?

like image 349
Anduin Avatar asked Nov 07 '18 03:11

Anduin


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr. Stroustroupe.

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

Is C programming hard?

C is more difficult to learn than JavaScript, but it's a valuable skill to have because most programming languages are actually implemented in C. This is because C is a “machine-level” language. So learning it will teach you how a computer works and will actually make learning new languages in the future easier.


2 Answers

If you truly just want to fire and forget. Simply don't call use await.

// It is a good idea to add CancellationTokens var asyncProcedure = SomeHTTPAction(cancellationToken).ConfigureAwait(false);  // Or If not simply do: var asyncProcedure = SomeHTTPAction().ConfigureAwait(false); 

If you want to use the result output later its gets trickier. But if it is truly fire and forget the above should work

A Cancellation token allows interrupts and canceling procedures. If you are using Cancellation token you will need to use it everywhere from the retrieval straight through to the calling method (Turtles all the way down).

I used ConfigureAwait(false) to prevent deadlocks. Here for more information

like image 166
Cornelis Avatar answered Sep 17 '22 22:09

Cornelis


A standalone discard is the best way to avoid this warning.

_ = Task.Run(() =>  _emailService.SendEmailAsync()); 

Discards are dummy variables and can be used to ignore the Task object returned by an asynchronous operation.

https://docs.microsoft.com/en-us/dotnet/csharp/discards#a-standalone-discard

like image 20
user2866442 Avatar answered Sep 18 '22 22:09

user2866442