事件处理程序的C#Async void收到警告/错误

事件处理程序的C#Async void收到警告/错误,c#,async-await,C#,Async Await,我理解异步不应该使用void作为返回类型,除非它是一个事件处理程序。但我有上面的代码片段,当我在项目设置中启用“警告为错误”时,我在编译代码时遇到了上面的错误 RECS0165异步方法“”不应返回void 如果删除async,则会出现另一个编译错误 “await”运算符只能在异步lambda中使用 表情。考虑用“异步”标记lambda表达式 修饰语 建议的修复方法是向匿名函数添加async。这是一个死锁 我做错什么了吗 重现问题的步骤如下: 在VS2017中创建一个空白的UWP项目,它将创建a

我理解异步不应该使用
void
作为返回类型,除非它是一个事件处理程序。但我有上面的代码片段,当我在项目设置中启用“警告为错误”时,我在编译代码时遇到了上面的错误

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, () =>
            {
    
            });
        }
    }
    
    }


勾选事件处理程序委托不正确

使用

或者对
e

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

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

勾选事件处理程序委托不正确

使用

或者对
e

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

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

问题实际上来自重构要素


问题实际上来自重构要素


代理不正确
async(sender,e)=>
或为
e
委托使用
eventag
派生类是不正确的
async(sender,e)=>
或为
e
使用
EventArg
派生类将代码更改为
this.refreshTimer.Tick+=async(sender,e)=>{wait this.DisplayMostRecentLocationData(string.Empty);}但仍然存在相同的编译错误。或者
this.refreshTimer.Tick+=async(对象发送方,EventArgs e)=>{wait this.DisplayMostRecentLocationData(string.Empty);}相同的编译错误。@hardywang,鉴于我不知道您的显示内容。。。我用
refreshTimer.Tick+=async(sender,e)=>{await Task.Run(()=>{});}测试了它
refreshTimer.Tick+=async(对象发送方,事件参数e)=>{wait Task.Run(()=>{});}并且编译得很好。编译错误消息正是我在原始帖子中引用的。我还添加了一个完整的示例代码来演示这个问题但仍然存在相同的编译错误。或者
this.refreshTimer.Tick+=async(对象发送方,EventArgs e)=>{wait this.DisplayMostRecentLocationData(string.Empty);}相同的编译错误。@hardywang,鉴于我不知道您的显示内容。。。我用
refreshTimer.Tick+=async(sender,e)=>{await Task.Run(()=>{});}测试了它
refreshTimer.Tick+=async(对象发送方,事件参数e)=>{wait Task.Run(()=>{});}并且编译得很好。编译错误消息正是我在原始帖子中引用的。我还添加了一个完整的示例代码来演示这个问题。