Ejrr1085
Ejrr1085

Reputation: 1071

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.

Upvotes: 3

Views: 728

Answers (1)

Alexander Goldabin
Alexander Goldabin

Reputation: 1934

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

Upvotes: 10

Related Questions