我正在为Windows 8编写Windows应用商店应用玩具应用。 它只有一个xaml页面,其中包含TextBlock
。该页面具有类MyTimer为DataContext
:Windows应用商店应用UI更新
this.DataContext = new MyTimer();
MyTimer
实现INotifyPropertyChanged
和财产Time
的更新与定时器制成:
public MyTimer(){
TimerElapsedHandler f = new TimerElapsedHandler(NotifyTimeChanged);
TimeSpan period = new TimeSpan(0, 0, 1);
ThreadPoolTimer.CreatePeriodicTimer(f, period);
}
与
private void NotifyTimeChanged(){
if (this.PropertyChanged != null){
this.PropertyChanged(this, new PropertyChangedEventArgs("Time"));
}
}
的TextBlock
有数据绑定时间
<TextBlock Text="{Binding Time}" />
当我运行应用程序,我有以下异常:
System.Runtime.InteropServices.COMException was unhandled by user code
随着消息
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
真正的问题是,我更新类MyTimer的财产,不是GUI本身, 我无法弄清楚,但我认为解决方案应该使用类似this one的东西。
非常感谢。这表明我每次使用异步调用时都需要使用SynchronizationContext ...我会考虑使用async关键字来做类似的事情。 – Gabber 2012-03-29 22:23:16
是的,如果你使用C#4.5的关键字,你会默认得到这个。 – 2012-03-29 23:39:26
感谢您的回答!我只想添加一个旁注:如果你想在UI上下文中回调,确保在UI已经建好的时候捕获'SynchronizationContext'(我使用'OnLaunched'事件处理器来完成它),否则您抓取的上下文将无法使用。进一步阅读:http://www.codeproject.com/Articles/31971/Understanding-SynchronizationContext-Part-I – Lvsti 2012-09-25 12:48:59