将UserControls异步添加到网格



我正在使用一个WPF应用程序,在应用导航时遇到问题,屏幕冻结,所以我想实现异步

我的导航方法:我创建一个网格,并将User控件添加到该网格的children属性中由于我在许多不同的用户控件上有很多UI元素,它冻结了应用程序

我想在加载窗口时添加一个异步的用户控件,我的想法是使用异步等待关键字,但显然我使用错误了,我已经研究过了,不明白为什么即使在有异步等待之后也建议使用调度器,所以我想遵循这种方式(异步/等待(

这只是实际交易的一个示例问题

这是代码

private async void grid1_Loaded(object sender, RoutedEventArgs e)
{
txtb1.Text = "";
var watch = System.Diagnostics.Stopwatch.StartNew();
await gy();
watch.Stop();
var elapsedtm = watch.ElapsedMilliseconds;
txtb1.Text += $"TOTAL TIME {elapsedtm} nnn";
}
private async Task gy() 
{
////////////

Y1 child1 = new Y1();
await Task.Run(() => grid1.Children.Add(child1));

///////////
}
private async void grid1_Loaded(object sender, RoutedEventArgs e)
{
txtb1.Text = "";
var watch = System.Diagnostics.Stopwatch.StartNew();
//Asynchronous execution of the "gy" method in the UI thread.
await Dispatcher.InvokeAsync(gy);
watch.Stop();
var elapsedtm = watch.ElapsedMilliseconds;
txtb1.Text += $"TOTAL TIME {elapsedtm} nnn";
}
// This method can only be called on the main UI thread.
private void gy()
{
////////////
UIElement child1 = new Y1();
grid1.Children.Add(child1);
///////////
}

如果在gy方法中有一些不使用UI元素的长期操作,并且您需要将主UI线程从执行中释放出来,那么这个选项:

private async void grid1_Loaded(object sender, RoutedEventArgs e)
{
txtb1.Text = "";
var watch = System.Diagnostics.Stopwatch.StartNew();

await gy();
watch.Stop();
var elapsedtm = watch.ElapsedMilliseconds;
txtb1.Text += $"TOTAL TIME {elapsedtm} nnn";
}
private async Task gy()
{
// Here's some lengthy code, but in which there are no calls to UI elements.
////////////
await grid1.Dispatcher.BeginInvoke(new Action(() =>
{
UIElement child1 = new Label() { Content = "Hello" };
grid1.Children.Add(child1);
}));
///////////
// Here's some lengthy code, but in which there are no calls to UI elements.
}

最新更新