WPF/C# 中的异步任务和 RoutedEventHandler 出现问题
Trouble with Async Task and RoutedEventHandler in WPF/C#
我有一个带有按钮的用户控件,该按钮用于 Window 和 RoutedEventHandler
:
用户控件:
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)
{
....
}
但我需要调用 CntBarraHerramientas_IniciarPLC_Click
中的 async
方法,所以我将 void
return 类型更改为 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.
问题是如何使用 RoutedEventHandler
调用 async
方法?因为从 Button 单击事件调用的 async
方法有效。
事件处理程序应该是 async void
。这是少数几个 async void
而不是 async Task
的地方之一
我有一个带有按钮的用户控件,该按钮用于 Window 和 RoutedEventHandler
:
用户控件:
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)
{
....
}
但我需要调用 CntBarraHerramientas_IniciarPLC_Click
中的 async
方法,所以我将 void
return 类型更改为 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.
问题是如何使用 RoutedEventHandler
调用 async
方法?因为从 Button 单击事件调用的 async
方法有效。
事件处理程序应该是 async void
。这是少数几个 async void
而不是 async Task