Lightswitch C#MessageBoxResult错误(UnautherizedAccessException:无效的跨线程访问)

时间:2015-05-21 20:17:37

标签: c# string messagebox lightswitch-2013

我正在慢慢开始使用Lightswitch进行一些我们拥有的小程序项目,但是我遇到了一个问题,我已经查看了几个帖子和日志,并且此时尚未找到解决方案。这里的任何帮助将不胜感激。

作为一个说明;我正在使用Visual Studio 2013 Ultimate。

我遇到的错误是UnauthorizedAccessException was unhandled by user code

我遇到问题的代码段粘贴在下面,用户点击按钮也会调用此段。这将用于捕获用户选择“确定”或“取消”,并根据用户的选择执行单独操作。

public void Restart_Prompt()
{
    MessageBoxResult result = MessageBox.Show("Yippy", "Hello", MessageBoxButton.OKCancel);

    if (result == MessageBoxResult.OK)
    {
        MessageBox.Show("Selected option was Ok");
    }
    else
    {
        MessageBox.Show("Selected option was Cancel...");
    }
}

同样,对此问题的任何指示或帮助都将不胜感激。

如果有人有兴趣,这是错误的详细文本:

{System.UnauthorizedAccessException: Invalid cross-thread access.
   at MS.Internal.XcpImports.CheckThread()
   at MS.Internal.XcpImports.MessageBox_ShowCore(Window window, String messageBoxText, String caption, UInt32 type)
   at System.Windows.MessageBox.ShowCore(Window window, String messageBoxText, String caption, MessageBoxButton button)
   at System.Windows.MessageBox.Show(String messageBoxText, String caption, MessageBoxButton button)
   at LightSwitchApplication.INVENTORiesListDetail.Restart_Prompt()
   at LightSwitchApplication.INVENTORiesListDetail.Restart_ASI_Execute()
   at LightSwitchApplication.INVENTORiesListDetail.DetailsClass.MethodSetProperties._Restart_ASI_InvokeMethod(DetailsClass d, ReadOnlyCollection`1 args)
   at Microsoft.LightSwitch.Details.Framework.Internal.BusinessMethodImplementation`2.<TryInvokeMethod>b__5()
   at Microsoft.LightSwitch.Utilities.Internal.UserCodeHelper.CallUserCode(Type sourceType, String methodName, String instance, String operation, ILoggingContext context, Action action, String additionalText, Func`1 getCompletedMessage, Boolean tryHandleException, Boolean swallowException, Exception& exception)}

1 个答案:

答案 0 :(得分:1)

在.Net - WPF和WinForms中 - UI是线程仿射。换句话说,所有与UI的交互都必须在UI线程上进行。在WPF中,这是通过Dispatcher类型实现的,而在WinForms中,它是通过每个控件上的Invoke方法实现的。您的方法是从后台线程调用的,因此您需要将调用封送到UI线程以防止出错。在灯开关我认为是这样的:

Dispatchers.Main.BeginInvoke(()=>
{
    // message box method call here
});
相关问题