Nul*_*rty 4 c# wpf multithreading
在我的C#WPF应用程序中,我有一个DataGrid正上方,TextBox用户可以在键入时搜索和过滤网格.如果用户快速键入,则在键入后2秒内不会显示任何文本,因为UI线程太忙于更新网格.
由于大部分延迟都在UI端(即过滤数据源几乎是即时的,但重新绑定和重新渲染网格很慢),多线程并没有帮助.然后我尝试将网格的调度程序设置为较低级别,同时网格更新,但这也没有解决问题.这里有一些代码......关于如何解决这类问题的任何建议?
string strSearchQuery = txtFindCompany.Text.Trim();
this.dgCompanies.Dispatcher.BeginInvoke(DispatcherPriority.ApplicationIdle, new Action(delegate
{
//filter data source, then
dgCompanies.ItemsSource = oFilteredCompanies;
}));
Run Code Online (Sandbox Code Playgroud)
使用ListCollectionView作为GridS的ItemsSource并更新Filter比重新分配ItemsSource要快得多.
通过简单地刷新搜索词文本属性的setter中的View,下面的示例过滤了100000行,没有明显的延迟.
视图模型
class ViewModel
{
private List<string> _collection = new List<string>();
private string _searchTerm;
public ListCollectionView ValuesView { get; set; }
public string SearchTerm
{
get
{
return _searchTerm;
}
set
{
_searchTerm = value;
ValuesView.Refresh();
}
}
public ViewModel()
{
_collection.AddRange(Enumerable.Range(0, 100000).Select(p => Guid.NewGuid().ToString()));
ValuesView = new ListCollectionView(_collection);
ValuesView.Filter = o =>
{
var listValue = (string)o;
return string.IsNullOrEmpty(_searchTerm) || listValue.Contains(_searchTerm);
};
}
}
Run Code Online (Sandbox Code Playgroud)
视图
<TextBox Grid.Row="0" Text="{Binding SearchTerm, UpdateSourceTrigger=PropertyChanged}" />
<ListBox ItemsSource="{Binding ValuesView}"
Grid.Row="1" />
Run Code Online (Sandbox Code Playgroud)