Search code examples
c#stringmessageboxlightswitch-2013

Lightswitch C# MessageBoxResult Error (UnautherizedAccessException : Invalid Cross-Thread Access)


I'm slowly starting to get into using Lightswitch for some of the small program projects we have but I am encountering an issue that I have looked through several posts and logs and have yet to find a solution at this time. Any help here would be appreciated.

As a note; I'm using Visual Studio 2013 Ultimate.

The Error I'm having is UnauthorizedAccessException was unhandled by user code.

The code segment I'm having my issue with is pasted just below, this segment is also being called by the user clicking on a button. This is to be used to catch a user selection of Ok or Cancel and do a separate action based on the user's choice.

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...");
    }
}

Again, any pointers or assistance on this issue would be appreciated.

Here is the detail text of the error if anyone is interested:

{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)}

Solution

  • In .Net - WPF and WinForms - the UI is thread affine. In other words all interaction with the UI has to occur on the UI thread. In WPF this is achieved via the Dispatcher type and in WinForms it's via the Invoke method on each control. Your method is being called from a background thread so you need to marshal the call onto the UI thread to prevent the error. In light switch I think It is this:

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