Wpf 视图模型调用中的调用方法占用/消耗大量时间
嗨,我试着解决这个问题。我有与MVVM设计的WPF应用程序。我使用Caliburn微框架和注入式MEF 在WPF应用程序中,我使用来自外部程序集的服务。它工作得很好 问题是。我将可观察字典绑定到列表框。列表框可以由0到400个项目组成。 我在列表框项目上有数据模板,它包含图像和som文本框。列表框就像 skype或google talk中的联系人列表 我从服务中每隔3-4秒调用一次方法,它将新数据作为字典返回。带有此数据的aj刷新列表框 我的代码视图模型如下所示:Wpf 视图模型调用中的调用方法占用/消耗大量时间,wpf,multithreading,mvvm,background,caliburn.micro,Wpf,Multithreading,Mvvm,Background,Caliburn.micro,嗨,我试着解决这个问题。我有与MVVM设计的WPF应用程序。我使用Caliburn微框架和注入式MEF 在WPF应用程序中,我使用来自外部程序集的服务。它工作得很好 问题是。我将可观察字典绑定到列表框。列表框可以由0到400个项目组成。 我在列表框项目上有数据模板,它包含图像和som文本框。列表框就像 skype或google talk中的联系人列表 我从服务中每隔3-4秒调用一次方法,它将新数据作为字典返回。带有此数据的aj刷新列表框 我的代码视图模型如下所示: private D
private DispatcherTimer _dispatcherTimer;
private MyObservableDictionary<string, UserInfo> _friends;
//temp
private MyObservableDictionary<string, UserInfo> _freshFriends;
//bind on listbox
public MyObservableDictionary<string, UserInfo> Friends
{
get { return _friends; }
set
{
_friends = value;
NotifyOfPropertyChange(() => Friends);
}
}
//in constructor of view model I have this:
_dispatcherTimer = new DispatcherTimer();
_dispatcherTimer.Tick += DispatcherTimer_Tick;
_dispatcherTimer.Interval = TimeSpan.FromSeconds(3);
_dispatcherTimer.Start();
// on timer tick I call method from service
private void DispatcherTimer_Tick(object sender, EventArgs eventArgs)
{
//get new data from server
//method GetFriends take much of time
_freshFriends = _service.GetFriends(Account);
//delete old data
_friends.Clear();
//refresh
foreach (var freshFriend in _freshFriends)
{
Friends.Add(freshFriend);
}
}
private dispatchermer\u dispatchermer;
私人MyObservableDictionary\u friends;
//临时工
私人MyObservableDictionary\u freshFriends;
//在列表框上绑定
公共MyObservableDictionary好友
{
获取{return\u friends;}
设置
{
_朋友=价值;
财产变更通知(()=>朋友);
}
}
//在视图模型的构造函数中,我有以下内容:
_Dispatchermer=新Dispatchermer();
_Dispatchermer.Tick+=Dispatchermer\u Tick;
_Dispatchermer.Interval=时间跨度(从秒开始)(3);
_dispatchermer.Start();
//在计时器滴答声中,我从服务调用方法
私有void Dispatcher_Tick(对象发送方,EventArgs EventArgs)
{
//从服务器获取新数据
//方法GetFriends花费大量时间
_freshFriends=_service.GetFriends(帐户);
//删除旧数据
_朋友们;
//刷新
foreach(var freshFriend in_freshFriends)
{
添加(freshFriend);
}
}
正如我所说的,问题是从服务中获取好友的方法花费了很多时间,我的应用程序冻结了
如何解决这个问题?在winforms应用程序中,我使用后台工作程序,但这是我第一个使用MVVM的WPF应用程序。是否存在任何“模式”或“设计”如何调用视图模型类中耗费大量时间的方法?在另一个线程中调用此方法?正如其他人所建议的,您可以在WPF应用程序中使用
BackgroundWorker
,或者如果您使用的是.NET 4,则使用。斯蒂芬·克利里(Stephen Cleary)在TPL上发表了一篇很好的帖子,与这里的BackgroundWorker
相比-BackgroundWorker在WPF中的工作与在WinForms中的工作一样好。正如@Wonko所说的那样-你可以在另一个线程(例如线程池中的线程)上生成服务请求,使用BackgroundWorker等-当结果返回时,通知主UI线程并填充列表框。这是一个线程问题,而不是WPF/MVVM问题。