Proper way to "fire and forget" async Tasks or run it in background

I need to run some async tasks which result I never gonna use anywhere and I don’t care when it will be finished.

For example, I might need my Discord client to respond on some command like this:

// .command
await StartLongAsyncTaskThatMayTakeForeverToCompleteAndSay("I'm late");
await Context.Message.ReplyAsync("Immediately say hi"));
// => "Immediately say hi"
// *few seconds later*
// => "I'm late"

Should I do it with: await StartLongAsyncTask().ConfigureAwait(false); or _ = StartLongAsyncTask(); or should I use Task.Run(() => {} );, and what is the difference?

>Solution :

Well you definitely don’t want to await your long running task and then reply after, you seem to want to reply right away and let the long running task run its course:

// .command
_ = StartLongAsyncTaskThatMayTakeForeverToCompleteAndSay("I'm late");
await Context.Message.ReplyAsync("Immediately say hi"));
// => "Immediately say hi"
// *few seconds later*
// => "I'm late"

and what is the difference

The difference between the last 2 options on your list (the first one I should think is obvious) is that the Task.Run version runs the async function on the thread pool, which you should never manually do for any sort of well behaved API, while simply calling the task runs it (or at least starts it) on your own thread (which is perfectly fine for I/O bound operations).

Leave a Reply