Modal message box from background thread

I noticed that there appears to be inconsistent behavior when the MessageBox is modal.

First run MessageBox from the user interface thread. This results in a modal MessageBox, as expected:

void MainThreadClick(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Hello!");
    }

Next, start from the background thread. This leads to the creation of a Modess MessageBox, I assume because it is not in the user interface thread?

void WorkerThreadClick(object sender, RoutedEventArgs e)
    {
        ThreadPool.QueueUserWorkItem((x) =>
        {
            MessageBox.Show("Hello!");
        });
    }

Further, launching from the background thread, but sent to the user interface thread, causes it to become modal again:

void WorkerThreadClick(object sender, RoutedEventArgs e)
    {
        ThreadPool.QueueUserWorkItem((x) =>
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                MessageBox.Show("Hello!");
            });
        });
    }

And finally, this is strange, as described above, but using the FileSystemWatcher stream leads to the Modeless dialog. Why is this? ... it is called in the user interface thread, so why is it not modal, as in the previous example?

public MainWindow()
    {
        InitializeComponent();

        m_watcher = new FileSystemWatcher()
        {
            Path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            NotifyFilter = NotifyFilters.LastWrite,
            IncludeSubdirectories = true,
            Filter = "*.*"
        };

        m_watcher.Changed += OnFileSystemResourceChanged;
        m_watcher.EnableRaisingEvents = true;
    }

    void OnFileSystemResourceChanged(object _sender, FileSystemEventArgs _args)
    {
        Application.Current.Dispatcher.Invoke(() =>
        {
            MessageBox.Show("Hello!");
        });
    }

, MessagBox.Show(), , , .

?

+4
1

. , , (FileSystemWatcher) ( , ).

, , .

2

void WorkerThreadClick(object sender, RoutedEventArgs e)
{
    ThreadPool.QueueUserWorkItem((x) =>
    {
        MessageBox.Show("Hello!");
    });
}

, Modeless - MainWindow, .

FileSystemWatcher Modeless, MainWindow, , MessageBox ( , - . ).

Shutdown

void OnFileSystemResourceChanged(object sender, FileSystemEventArgs args)
    {
        Application.Current.Dispatcher.Invoke(() =>
            {
                Application.Current.ShutdownMode=ShutdownMode.OnMainWindowClose;
                MessageBox.Show("Test");
            });
    }

, MainWindow, Application , MessageBox . , .

+1

All Articles