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?
CodePudding user response:
It hugely depends on what StartLongAsyncTaskThatMayTakeForeverToCompleteAndSay
is and the context, for example in some cases assigning invocation result to a task variable and awaiting it after the second call can be ok:
var task = StartLongAsyncTaskThatMayTakeForeverToCompleteAndSay("I'm late");
await Context.Message.ReplyAsync("Immediately say hi"));
await task;
Or just:
await Task.WhenAll(StartLongAsyncTaskThatMayTakeForeverToCompleteAndSay("I'm late"),
Context.Message.ReplyAsync("Immediately say hi")));
For differences between the two - see Why should I prefer single 'await Task.WhenAll' over multiple awaits?.
CodePudding user response:
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).