Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with Async Task and RoutedEventHandler in WPF/C#

I have an User Control with a Button which 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.

like image 304
Ejrr1085 Avatar asked Jan 25 '26 04:01

Ejrr1085


1 Answers

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

like image 149
Alexander Goldabin Avatar answered Jan 27 '26 18:01

Alexander Goldabin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!