在带有MVVM Light的WP7项目中引发未经授权的AccessException(无效的跨线程访问)
本文关键字:AccessException 授权 无效 访问 线程 MVVM Light WP7 项目 | 更新日期: 2023-09-27 18:22:18
我正在使用MVVM light toolkit的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()
这是因为什么?提前感谢!
MVVVMLight可以使用DispatcherHelper
确保代码在UI线程上运行(您的问题)
例如
DispatcherHelper.CheckBeginInvokeOnUI(YOUR-ACTION);
这是我的解决方案:
http://wp8xp.blogspot.com.es/2013/02/llamadas-asincronas-internet-haciendo.html
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
});