忽略异步Task方法的返回值 [英] Ignoring the return value from an async Task method

查看:246
本文介绍了忽略异步Task方法的返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下:在我的WPF应用程序中,我想始终保持运行着各种功能的循环。我想到了这种模式:

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.

推荐答案

正如chris的回答中所述,正确的解决方案是将事件处理程序转换为 async void 方法,然后使用 await ,这样可以正确传播异常。

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.

但是如果您真的想忽略 Task ,则可以将其分配给变量:

But if you really want to ignore the Task, then you can assign it to a variable:

var ignored = SomeProcessAsync();

或者在C#7.0中,您可以使用丢弃:

Or in C# 7.0, you can use discard:

_ = SomeProcessAsync();

这篇关于忽略异步Task方法的返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆