据我所知,这里最好的选择之一是添加一个异步方法,然后等待“heavy”函数执行其结果
最好的选择是使用
Task.Run
将繁重的处理转移到线程池,并使用
await
以检索其结果。
目前的代码使用
任务.运行
移动到线程池,然后立即转身使用
Dispatcher
以在执行繁重的处理之前移回UI线程。因此,它阻塞了UI线程。
这个特定的DataGrid显示的是CollectionView,它不是线程安全的。
没错,您不能从线程池线程更新数据绑定对象。
最好的解决方案是
分离
UI更新的繁重处理,如下所示:
public async void Window_Loaded(object sender, RoutedEventArgs e)
{
await firstLoadAsync();
}
private List<FilterType> InitializeFilter()
{
//... some lines of code that takes some time to run.
}
private async Task firstLoadAsync()
{
LW.Title = "Loading...";
LW.Show();
filterTextBox.Text = defaultSearch;
var filterData = await Task.Run(() => InitializeFilter()); // Get the plain data on a background thread
myCollectionView = new CollectionView(filterData); // Update the UI
if (LW != null)
{
LW.closable = true;
LW.Close();
}
}