Task has a wrong return type
Solution 1
Button click events are one of the few method signatures where async void
is acceptable. Change your method to read
public async void btn1_ClickAsync(object sender, RoutedEventArgs e)
and you should be OK.
Solution 2
Event handlers need to be async void
methods:
public async void btn1_ClickAsync(object sender, RoutedEventArgs e)
Solution 3
Since it's an event handler it should be async void
public async void btn1_ClickAsync(object sender, RoutedEventArgs e)
Note that async void
is a special case and should normally be avoided. See async/await - when to return a Task vs void? for details.
Solution 4
WPF events are usually RoutedEventHandler
, i.e. they have the signature void RoutedEventHandler(object sender, RoutedEventArgs e)
. Your btn1_ClickAsync
doesn't match that, hence the error message.
You can fix it by using public async void btn1_ClickAsync(...)
. Event handlers are also about the only time you would use an async void
function.
vhkvua
Updated on July 21, 2022Comments
-
vhkvua almost 2 years
What wrong? and how to fix??I'm trying to learn a new subject in c#-task. and when I run I got error message:
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 designer:
<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>
-
Abdu Imam almost 4 yearsyes thanks it is work but we need to ensure that the Page is marked <%@ Page Async="true" %> on asp.net page