WPF/C# 中的异步任务和 RoutedEventHandler 出现问题

Ejr*_*085 2 c# wpf routed-events async-await

我有一个带有按钮的用户控件,可以从带有以下内容的窗口中使用RoutedEventHandler

用户控制:

public event RoutedEventHandler IniciarPLC_Click;
private void BtnIniciarPLC_Click(object sender, RoutedEventArgs e)
{
   .....
   if (IniciarPLC_Click != null)
   {
        IniciarPLC_Click(this, new RoutedEventArgs());
   }
   ......
}
Run Code Online (Sandbox Code Playgroud)

窗户:

XAML:

<ucUserControl x:Name="cntBarraHerramientas"  IniciarPLC_Click="CntBarraHerramientas_IniciarPLC_Click"/>
Run Code Online (Sandbox Code Playgroud)

C#:

private void CntBarraHerramientas_IniciarPLC_Click(object sender, RoutedEventArgs e)
{
    ....       
}
Run Code Online (Sandbox Code Playgroud)

但我需要调用async中的方法CntBarraHerramientas_IniciarPLC_Click,因此我更改了void返回类型并async Task使用以下方法调用该方法await

private async Task CntBarraHerramientas_IniciarPLC_Click(object sender, RoutedEventArgs e)
{
    await AsyncMethod(...);
}
Run Code Online (Sandbox Code Playgroud)

我有这个错误:

无法从文本“CntBarraHerramientas_IniciarPLC_Click”创建“IniciarPLC_Click”。' ArgumentException:您无法链接到目标方法,因为其安全透明度或签名与委托类型的安全透明度或签名不兼容。

问题是我如何调用async方法RoutedEventHandler?因为async从按钮单击事件调用的方法有效。

小智 9

事件处理程序应该是async void. 这是为数不多的几个可以代替async void的地方之一async Task

  • 是的,使用 private async void CntBarraHerramientas_IniciarPLC_Click(object sender, RoutedEventArgs e) 可以工作,谢谢。 (2认同)