我是新来的异步编程和WP8,这是我的第一个应用程序,我有Dispatcher.BeginInvoke(..)的Windows Phone 8 Dispatcher.BeginInvoke不工作异步
中的一些问题的看法的背后我的代码类,我试图在第二个选项卡的数据透视scree异步加载数据。
这里是我现在所拥有的:
public partial class ReminderPivot : PhoneApplicationPage
{
#region Reminder Members
private ReminderViewModel _model;
private IRepository _repository;
#endregion Reminder Members
#region Constructors
public ReminderPivot()
{
InitializeComponent();
_model = new ReminderViewModel();
_repository = new LocalStorageRepository();
LoadData();
LoadAsyncData();
this.DataContext = _model;
}
#endregion Constructors
public void LoadData()
{
IEnumerable<Reminder> activeList = _repository.GetRemindersByStatusId(2);
if (activeList != null)
{
foreach (var reminder in activeList)
{
_model.ActiveReminders.Add(reminder);
}
}
}
public void LoadAsyncData()
{
Action action =() =>
{
Thread.Sleep(5000);
IEnumerable<Reminder> inactiveList = _repository.GetRemindersByStatusId(3);
if (inactiveList != null)
{
_model.InctiveReminders = new System.Collections.ObjectModel.ObservableCollection<Reminder>(inactiveList);
}
};
Dispatcher.BeginInvoke(action);
}
的事情是,这仍然让我的UI线程。我在这里错过了什么?
编辑: 这个想法是加载数据异步到ViewModel ObservableCollection这是ModelBinded在XAML。
,如果我尝试拨打电话异步另一个线程与Task.Factory(...)等让说,这个崩溃,因为我改变从另一个线程没有UI线程的结合。
我没有看到你的代码,表明异步使用...'Dispatcher.BeginInvoke'将在UI线程上执行代码的任何东西,它才刚刚派往是稍后执行! – 2013-03-01 19:23:07
Hi @PedroLamas。那么问题是,我如何加载是异步?如果我Task.Factory(..),并尝试在一个单独的线程创建它,那么它将会崩溃,因为我的列表我更新被绑定到ListBox .. – 2013-03-01 19:27:47
在我看来,使用'Task.Factory'是绝对是最好的可能性在这里... – 2013-03-01 19:34:36