dotnet / dotnet/wpf

PrintDialog in multithreaded window throws System.InvalidOperationException

Open
#486 1 comment 0 reactions 0 assignees View on GitHub
Bug
Dominant language
C#
Stars
7.7k
Forks
1.3k
Avg merge
1d 11h
Merged PRs (30d)
61

Description

Hi, I am using a secondary UI thread for opening the MainWindow of my WPF application as shown in thefollowing code snippet.
```
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
Thread thread = new Thread(() => {
MainWindow mainWindow = new MainWindow();
mainWindow.Show();
System.Windows.Threading.Dispatcher.Run();
});
thread.IsBackground = false;
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
}
```
In a button click I try to open show a PrintDialog using the following code snippet.

```
PrintDialog printDialog = new PrintDialog();
printDialog.ShowDialog();
```

When this button is clicked, the app crashes with the following exception: The calling thread cannot access this object because a different thread owns it.


PrintDialog uses a private class Win32PrintDialog which seems to access Application.Current.MainWindow which is the cause for the exception and I have checked this in the following reference source link.

https://referencesource.microsoft.com/#PresentationFramework/src/Framework/MS/Internal/Printing/Win32PrintDialog.cs,9e8f593d2c265d9c

I have attached a sample here to replicate this scenario. printdialogdemo.zip

Is there any way to avoid this exception and show the PrintDialog in a multithreaded window?

Please share your solution for this. Thanks in advance.

Regards,

Mohanram A.

_This issue has been moved from https://developercommunity.visualstudio.com/content/problem/515387/printdialog-in-multithreaded-window-throws-systemi.html
VSTS ticketId: 837184_
_These are the original issue comments:_
(no comments)
_These are the original issue solutions:_
(no solutions)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.