Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring the return value from an async Task method

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.

like image 763
boot4life Avatar asked Nov 28 '22 13:11

boot4life


2 Answers

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();
like image 124
svick Avatar answered Dec 12 '22 16:12

svick


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.

like image 37
chris Avatar answered Dec 12 '22 17:12

chris