C
C#15mo ago
TimberStalker

❔ Fire and forget

Is there a recommended way to call an async void, or to run an async task as fire and forget? I havent been able to find any that doesent cause a warning, and i would rather not supress it.
5 Replies
cap5lut
cap5lut15mo ago
simply dont await the task eg
class Program
{
public static async Task Main()
{
FireAndForgetAsync();
Console.WriteLine("This should print immediately");
await Task.Delay(2000);
Console.WriteLine("Bye, bye");
}
public static async Task FireAndForgetAsync()
{
await Task.Delay(1000);
Console.WriteLine("FireAndForgetAsync()");
}
}
class Program
{
public static async Task Main()
{
FireAndForgetAsync();
Console.WriteLine("This should print immediately");
await Task.Delay(2000);
Console.WriteLine("Bye, bye");
}
public static async Task FireAndForgetAsync()
{
await Task.Delay(1000);
Console.WriteLine("FireAndForgetAsync()");
}
}
Cattywampus
Cattywampus15mo ago
that will throw warning @cap5lut you should do it with _ discard also why you made it async/await when you're not planning to await it?
Becquerel
Becquerel15mo ago
you get a warning because if the async method throws an exception and you don't await it you won't catch the exception properly
Angius
Angius15mo ago
public void SynchronousMethod()
{
try {
_ = AsynchronousMethod();
} catch (Exception e) {
// log **everything** because no exceptions will be handled for you
}
}
public void SynchronousMethod()
{
try {
_ = AsynchronousMethod();
} catch (Exception e) {
// log **everything** because no exceptions will be handled for you
}
}
is about the only proper way to go about fire&forget
Accord
Accord15mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.