在UI定义一个TextBox和一个Button 测试异步函数更新UI。
UpdateSN
定义一个异步函数:
internal async Task ShowSN(string sn)
{
await this.txtSN.Dispatcher.BeginInvoke(new Action(() =>
{
txtSN.Text = sn;
}));
}
在Button Click事件中:
private async void btnUpdateSn_Click(object sender, RoutedEventArgs e)
{
Random rnd = new Random();
while (true)
{
await Task.Delay(1200);
int num = rnd.Next(1000, 9999);
await ShowSN($"04B648450000{num}");
}
}
UI每隔1.2秒,创建一个随机数字,并显示在UI上,动态更新UI,并且不阻塞UI线程。