简体   繁体   中英

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 :

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:

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

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 :

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 ? Because the async method calling from a Button click event work.

Event handler should be async void . It's one of the few places where you would have async void instead of async Task

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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