简体   繁体   English

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

[英]Trouble with Async Task and RoutedEventHandler in WPF/C#

I have an User Control with a Button wich is used from a Window with a RoutedEventHandler :我有一个带有 Button 的用户控件,它从带有RoutedEventHandler的窗口中使用:

UserControl:用户控件:

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

Window:窗户:

XAML: XAML:

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

C#: C#:

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

But I need call to an async method in CntBarraHerramientas_IniciarPLC_Click , so I changed the void return type by async Task and call the method with await :但是我需要调用CntBarraHerramientas_IniciarPLC_Clickasync方法,所以我通过async Task更改了void返回类型并使用await调用该方法:

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

And I have this error:我有这个错误:

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.

The question is how to I do call an async Method with RoutedEventHandler ?问题是如何使用RoutedEventHandler调用async方法? Because the async method calling from a Button click event work.因为从按钮单击事件调用的async方法有效。

Event handler should be async void .事件处理程序应该是async void It's one of the few places where you would have async void instead of async Task这是少数几个可以使用async void而不是async Task

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM