[英]UnauthorizedAccessException (Invalid cross-thread access) thrown in WP7 project with MVVM Light
我正在使用MVVM light工具箱的Messenger類來傳達WP7應用程序的不同部分。
從我的應用程序類接收消息時,我試圖使視圖進入不同的狀態。 在視圖的代碼背后,我注冊了消息:
Messenger.Default.Register<PageActionMessage>
(
this,
(action) => GoToPage(action)
);
並在收到時調用以下方法:
private object GoToPage(PageActionMessage action)
{
if (action.action == PageAction.TwitterAuthFinished)
{
if (IsoStoreHelper.CheckIfAuthorized())
{
VisualStateManager.GoToState(this, "TwitterSendPage", true); // The exception is thrown here
}
}
}
在我的另一堂課中,消息是通過以下方式廣播的:
var PageMsg = new PageActionMessage()
{
action = PageAction.TwitterAuthFinished
};
Messenger.Default.Send<PageActionMessage>(PageMsg);
視圖正確接收了此消息,但是在調用VisualStateManager的GoToState方法時,將引發帶有以下跟蹤的UnauthorizedAccessException(無效的跨線程訪問):
System.UnauthorizedAccessException was unhandled
Message=Invalid cross-thread access.
StackTrace:
at MS.Internal.XcpImports.CheckThread()
at System.Windows.DependencyObject.GetValueInternal(DependencyProperty dp)
at System.Windows.FrameworkElement.GetValueInternal(DependencyProperty dp)
at System.Windows.DependencyObject.GetValue(DependencyProperty dp)
at System.Windows.Controls.Panel.get_Children()
at MS.Internal.XcpImports.CheckThread()
at MS.Internal.XcpImports.Control_GetImplementationRoot(Control control)
at System.Windows.Controls.Control.get_ImplementationRoot()
at System.Windows.VisualStateManager.GoToState(Control control, String stateName, Boolean useTransitions)
at KidsBook.MainPage.GoToPage(PageActionMessage action)
at KidsBook.MainPage.<.ctor>b__0(PageActionMessage action)
at GalaSoft.MvvmLight.Helpers.WeakAction`1.Execute(PageActionMessage parameter)
at GalaSoft.MvvmLight.Helpers.WeakAction`1.ExecuteWithObject(Object parameter)
at GalaSoft.MvvmLight.Messaging.Messenger.SendToList[TMessage](PageActionMessage message, IEnumerable`1 list, Type messageTargetType, Object token)
at GalaSoft.MvvmLight.Messaging.Messenger.SendToTargetOrType[TMessage](PageActionMessage message, Type messageTargetType, Object token)
at GalaSoft.MvvmLight.Messaging.Messenger.Send[TMessage](PageActionMessage message)
at KidsBook.Twitter.OAuthClient.GetResponse(IAsyncResult result)
at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2)
at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadPool.WorkItem.doWork(Object o)
at System.Threading.Timer.ring()
這是什么原因 提前致謝!
這是我的解決方案:
http://wp8xp.blogspot.com.es/2013/02/llamadas-asincronas-internet-haciendo.html
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
});
使用MVVVMLight,您可以使用DispatcherHelper
來確保代碼在UI線程上運行(您的問題)。
例如
DispatcherHelper.CheckBeginInvokeOnUI(YOUR-ACTION);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.