c# - WPF/C# 中异步任务和 RoutedEventHandler 的问题

标签 c# wpf async-await routed-events

我有一个带有按钮的用户控件,它在带有 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)
{
    ....       
}

但我需要调用 async CntBarraHerramientas_IniciarPLC_Click 中的方法, 所以我改变了 void返回类型 async Task并使用 await 调用该方法:

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

我有这个错误:

Could not create a 'IniciarPLC_Click' from the text 'CntBarraHerramientas_IniciarPLC_Click'. ' ArgumentException: You cannot link to the target method because its security transparency or signature is not compatible with that of the delegated type.

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

最佳答案

事件处理程序应该是async void。它是少数几个用 async void 而不是 async Task

的地方之一

关于c# - WPF/C# 中异步任务和 RoutedEventHandler 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59954357/

相关文章:

c# - 如何从另一个类中运行的另一个线程更新 UI

c# - 从未完成的任务会怎样?他们是否妥善处置?

c# - 如何正确实现 TAP 方法?

c# - API 工作正常但不接受参数 c#

c# - 从集合 ObservableCollection 更新数据库

c# - 如何防止内容为空的标签折叠?

javascript - 没有正确理解 async/await/promise 的工作原理

c# - 对象上的 DragEnter 事件,AllowDrop=False

c# - 为什么我的汉字在c#字符串中显示不正确

c# - 如何在 Windows Universal App 中使用双工 wcf 服务