【问题标题】:Trouble with Async Task and RoutedEventHandler in WPF/C#WPF/C#中的异步任务和RoutedEventHandler问题
【发布时间】:2020-05-14 04:47:09
【问题描述】:

我有一个带有按钮的用户控件,该按钮在带有RoutedEventHandler 的窗口中使用:

用户控制:

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

窗口:

XAML:

<ucUserControl x:Name="cntBarraHerramientas"  IniciarPLC_Click="CntBarraHerramientas_IniciarPLC_Click"/>

C#:

private void CntBarraHerramientas_IniciarPLC_Click(object sender, RoutedEventArgs e)
{
    ....       
}

但我需要在CntBarraHerramientas_IniciarPLC_Click 中调用async 方法,所以我将void 返回类型更改为async Task,并使用await 调用该方法:

private async Task CntBarraHerramientas_IniciarPLC_Click(object sender, RoutedEventArgs e)
{
    await AsyncMethod(...);
}

我有这个错误:

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

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

【问题讨论】:

    标签: c# wpf async-await routed-events


    【解决方案1】:

    事件处理程序应该是async void。这是为数不多的有async void 而不是async Task 的地方之一

    【讨论】:

    • 是的,使用私有 async void CntBarraHerramientas_IniciarPLC_Click(object sender, RoutedEventArgs e) 工作,谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多