xaml页面,一个按钮,一个lable,lable用来更新等待的时间。点击按钮,每过1秒,label的数值+1,直到任务结束。
XML
<Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
<Button Content="Button" HorizontalAlignment="Left" Margin="350,0,0,0" VerticalAlignment="Center" Height="72" Width="149" Click="Button_Click"/>
<Label Content="0" HorizontalAlignment="Left" Margin="350,281,0,0" VerticalAlignment="Top" x:Name="Lab"/>
</Grid>
</Window>
.cs代码
cs
private async void Button_Click(object sender, RoutedEventArgs e)
{
bool isOk = false;
Wait((result)=>isOk = result);
while (!isOk)
{
//等待耗时任务结束,界面的Label加1
await Task.Delay(1000);
Lab.Content = Convert.ToInt32(Lab.Content) + 1;
}
}
private async void Wait(Action<bool> callback)
{
bool isok = false;
//耗时任务
for (int i = 0; i < 10; i++)
{
await Task.Delay(1000);
}
isok = true;
callback?.Invoke(isok);
}