任务的返回类型错误

时间:2018-08-26 09:03:06

标签: c# wpf task

怎么了?以及如何解决?我正在尝试学习c#-task中的新主题。当我运行时,我收到错误消息: Error CS0407 'Task MainWindow.btn1_ClickAsync(object, RoutedEventArgs)' has the wrong return type

 public async Task btn1_ClickAsync(object sender, RoutedEventArgs e)
            {
                txtState.Text = "btn1_Click started";
               await LongRunningFunc1();
                txtState.Text = "btn1_Click finished";

            }

        private async Task LongRunningFunc1()
        {
            txt1.Text = "Processing 1 .....";
            btn1.Content = "Wait";
            await Task.Delay(5000);
            txt1.Text = "Hello From Func1";
            btn1.Content = "Click";
        }

wpf设计器:

<Grid>
        <TextBlock Name="txtState" Margin="265,10,274,356"/>
        <TextBlock Name="txt1" Height="50" RenderTransformOrigin="0.966,-0.95" Margin="281,68,320,301"/>
        <TextBlock Name="txt2" Height="50" Margin="253,238,274,131" />
        <Button Name="btn1" Background="Red" Margin="281,127,300,208" Click="btn1_ClickAsync"></Button>
        <Button Name="btn2" Background="Aqua" Margin="298,309,311,27"></Button>
    </Grid>

4 个答案:

答案 0 :(得分:3)

按钮单击事件是可以接受async void的少数方法签名之一。更改您的阅读方式

public async void btn1_ClickAsync(object sender, RoutedEventArgs e)

您应该没事。

答案 1 :(得分:1)

事件处理程序必须是async void方法:

public async void btn1_ClickAsync(object sender, RoutedEventArgs e)

答案 2 :(得分:0)

由于它是事件处理程序,因此应为async void

public async void btn1_ClickAsync(object sender, RoutedEventArgs e)

请注意,这违反了所有(实际上是大多数)异步/任务规则。有关详细信息,请参见async/await - when to return a Task vs void?

答案 3 :(得分:0)

WPF事件通常为RoutedEventHandler,即它们具有签名void RoutedEventHandler(object sender, RoutedEventArgs e)。您的btn1_ClickAsync与之不符,因此出现错误消息。

您可以使用public async void btn1_ClickAsync(...)对其进行修复。事件处理程序也是大约只有一次使用async void函数的情况。