55

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 completion?

6
  • 1
    Just don't mark the function as async, so the function shouldn't expect its result to be awaited?
    – Amadan
    Nov 7, 2018 at 3:59
  • 3
    Possible duplicate of How to safely call an async method in C# without await Nov 7, 2018 at 4:00
  • The better approach is to have these operations run out of process i.e. publish to some queue like rabbitmq and have a subscriber pick up these messages and then send off emails/sms
    – JohanP
    Nov 7, 2018 at 4:00
  • What information have you found so far? A quick google for "C# async fire and forget" shows there is a lot of resource available for this.. Nov 7, 2018 at 4:00
  • Isn't this really a problem of design? What's the point of returning MyRespond before you know the operation to be complete or not?
    – user585968
    Nov 7, 2018 at 4:51

7 Answers 7

54

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://learn.microsoft.com/en-us/dotnet/csharp/discards#a-standalone-discard

1
  • 1
    This answer is correct. I am downvoting only because it is very similar to an earlier answer by MrMaavin. Oct 31, 2020 at 2:36
34

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


EDIT

See the second answer that uses 'Task.Factory.StartNew' I gave this answer some time ago. At the time I didn't realise that the way I did it at the time doesn't ensure completion.

1
  • 2
    "I used ConfigureAwait(false) to prevent deadlocks." -- The ConfigureAwait method configures the await. If you don't await it, then it has absolutely no effect. I won't prevent any deadlock, because there is no risk for a deadlock in the first place. Feb 15, 2023 at 8:14
10

If you need to use async in your function you can also use a discard variable and don't use await. This is also usefull if you have multiple async function calls but you don't need to wait for all of them.

public async function(){
    var tmp = await asyncfunction();
    ...
    _ = _httpClient.PutAsync(url, content);
    ...
}
7

As Amadan told in the comment that, you need to remove async from your function. then it will stop giving you the warning.

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

and Task.Factory.StartNew(() => _emailService.SendEmailAsync()); will indeed work on a new thread.

0

It all depends on what your Async method accepts. Normally it will accept a "special" class that also holds an event. You can subscribe your callback method to that event and pass it along with the method. When it's finished, your callback method will be called.

An example of this (for sockets) would be:

    public void CreateSocket()
    {
        Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        SocketAsyncEventArgs sockAsync = new SocketAsyncEventArgs();
        sockAsync.Completed += SockAsync_Completed;

        s.ConnectAsync(sockAsync);
    }

    private void SockAsync_Completed(object sender, SocketAsyncEventArgs e)
    {
        //Do stuff with your callback object.
    }

It all depends on what the method you are trying to call can accept. I would look at the documentation for more help on that specifically.

1
  • I have to admit, only after I read your answer I realized that OP question was not really specific and with a bit of bad luck could be misread. In general, what you wrote is true -- but unfortunatelly, you are describing not that "Async thing" the question asked about. There are several "async patterns" in the dotnet apis/etc. What you are referring here to, is event/callback-based async api. There's also IAsyncResult with classic Begin/End method pair, almost as old or even older. But here in this question, they asked about async/await pattern that was added in Net4.5 around 2013. Jul 14, 2023 at 9:53
-1

I am curious why this hasn't been suggested.

new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    //what ever code here...e.g.
    DoSomething();
    UpdateSomething();
}).Start();  

It just fires off a separate thread.

2
  • 5
    This will create a new thread and run method(s) on that new thread , which is quite expensive/resource consuming. Not an answer to the related question.
    – naltun
    Oct 9, 2020 at 3:23
  • Downvoting because whie it is SOME hint on how you COULD (if you don't care, or have a serious reason, etc) run an async action without waiting for it - the code and explanations provided doesn't contain a single 'async' or 'await' keywords, and they DO CHANGE how you would build your thread's body significantly. Jul 14, 2023 at 9:43
-3

I did part of user2866442's solution, but I am using an Action with a Lambda to supply what is executed async:

Action<object, long> sendEmail = (var1, id) => 
{
    try
    {
        //Execute some code here
    }
    catch (Exception ex) 
    { 
        Log.ErrorException("sendEmail Error: " + ex.Message, ex); //Using NLog here.
    } 
    //Dont throw any errors here -it doesnt matter because this an async 
};

_ = System.Threading.Tasks.Task.Run(() => sendEmail(var1, id));  
//Run our sendMail code above without waiting for it to finish. 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.