Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading