【问题标题】:C# Async void of event handler got warning/error事件处理程序的 C# Async void 收到警告/错误
【发布时间】:2017-10-18 01:27:07
【问题描述】:

我了解异步不应使用 void 作为返回类型,除非它是事件处理程序。但是我上面有代码 sn-p,当我在项目设置中打开警告作为错误时,我在编译代码时得到了上面的错误。

RECS0165 异步方法 '' 不应返回 void

如果我删除async,那么我会得到另一个编译错误

“await”运算符只能在异步 lambda 中使用 表达。考虑用“异步”标记这个 lambda 表达式 修饰符。

建议的解决方法是将async 添加到匿名函数中。这是一个死锁。

我在这里做错了吗?

重现问题的步骤:

  • 在VS2017中创建一个空白的UWP项目,它将创建app、xaml和MainPage.Xaml。
  • 在 MainPage.Xaml.cs 中添加以下代码

    命名空间 App4 { 使用系统; 使用 System.Threading.Tasks; 使用 Windows.ApplicationModel.Core; 使用 Windows.UI.Core; 使用 Windows.UI.Xaml; 使用 Windows.UI.Xaml.Controls;

    public sealed partial class MainPage : Page
    {
        private DispatcherTimer refreshTimer;
    
        public MainPage()
        {
            this.InitializeComponent();
    
            this.refreshTimer = new DispatcherTimer()
            {
                Interval = new TimeSpan(0, 0, 30)
            };
    
            refreshTimer.Tick += async (sender, e) => { await DisplayMostRecentLocationData(string.Empty); };
        }
    
        private async Task DisplayMostRecentLocationData(string s)
        {
            await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
    
            });
        }
    }
    

    }

【问题讨论】:

  • 委托不正确。 async (sender, e) => 或为e 使用EventArg 派生类

标签: c# async-await


【解决方案1】:

Tick 事件处理程序委托不正确。

使用

async (sender, e) => ...

或为e 使用EventArg 派生类

async (object sender, EventArgs e) => ...    

您当前拥有的是一个匿名对象,您正试图将其分配为事件处理程序。编译器不允许这样做,因此会出现错误。

【讨论】:

  • 已将代码更改为this.refreshTimer.Tick += async (sender, e) => { await this.DisplayMostRecentLocationData(string.Empty); };,但仍然存在相同的编译错误。或者this.refreshTimer.Tick += async (object sender, EventArgs e) => { await this.DisplayMostRecentLocationData(string.Empty); };同样的编译错误。
  • @hardywang,鉴于我不知道您的 Display... 方法是什么,我用 refreshTimer.Tick += async (sender, e) => { await Task.Run(() => { }); };refreshTimer.Tick += async (object sender, EventArgs e) => { await Task.Run(() => { }); }; 对其进行了测试,它编译得很好。
  • 编译错误消息正是我在原始帖子中引用的内容。而且我还添加了一个完整的示例代码来演示这个问题。
【解决方案2】:
猜你喜欢
  • 2014-06-17
  • 2012-09-02
  • 1970-01-01
  • 1970-01-01
  • 2021-05-16
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
  • 2014-02-09
相关资源
最近更新 更多