Search code examples
c#wpfdebuggingvisual-studio-2012openfiledialog

CrossThreadMessagingException WPF OpenFileDialog


I get this exception:

Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException was unhandled HResult=-2146232832 Message=An exception 'Microsoft.VisualStudio.Debugger.Runtime.CrossThreadMessagingException' occurred Source=Microsoft.VisualStudio.Debugger.Runtime StackTrace: at Microsoft.VisualStudio.Debugger.Runtime.Main.ThrowCrossThreadMessageException(String formatString) InnerException:

When I use this code:

    public string ShowOpenFileDialog(string initialPath, string filter = null)
    {
        var dialog = new OpenFileDialog()
        {
            InitialDirectory = Directory.Exists(initialPath) ? Path.GetDirectoryName(initialPath) : String.Empty,
            FileName = File.Exists(initialPath) ? Path.GetFileName(initialPath) : String.Empty,
            Filter = filter
        };

        if (dialog.ShowDialog() == true)
        {
            return dialog.FileName;
        }

        return String.Empty;
    }

I am not explicitly using multithreading, so what is causing this? It happens frequently during debugging, but not all the time. I've changed the method signature about a million times, because I was passing in ref/out parameters and thought they might be the cause.

edit: I'm calling it from the UI Thread. Button in View -> Command in ViewModel -> ShowOpenFileDialog.


Solution

  • Although I'm not still sure why this is happening, I've figured out how to fix in my case. I have multiple projects in my solution, and I've configured two startup projects (client + server). When I start both projects with debugging, it appears that the debugger has trouble with that. So I just switch off debugging for the project that matters least at the moment, so there is only one project for the debugger to handle.