Here's the scenario: In my WPF app I'd like to keep a loop running at all times that does various things. This pattern came to mind:
void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
SomeProcessAsync(); //throw away task
}
async Task SomeProcessAsync()
{
while (true)
{
DoSomething();
await Task.Delay(1000);
}
}
The call triggers a warning since the return value is unused. What is the cleanest way to silence that warning?
#pragma warning disable 4014
AddItemsAsync(); //throw away task
#pragma warning restore 4014
This works but it looks so nasty!
Btw, I also could have used a timer but I liked the simplicity of this loop.
As already mentioned in chris' answer, the right solution here is to turn the event handler into an async void
method and then use await
, so that exceptions are propagated correctly.
But if you really want to ignore the Task
, then you can assign it to a variable:
var ignored = SomeProcessAsync();
Or in C# 7.0, you can use discard:
_ = SomeProcessAsync();
You can make the event handler async:
async void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
{
await SomeProcessAsync(); //throw away task
}
Normally, async void
is bad, but it's necessary when an event handler is async and exceptions should be handled here instead of in whatever calls this. You can (and should) use the normal ConfigureAwait(false)
if SomeProcessAsync
doesn't need the UI context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With