2

I have a window which runs from a thread, let's call it MainThread, and a background thread which performs other non-graphical tasks.

Sometimes the background thread will call the MessageBox.Show(...) method (which is modal and stops the background thread). Before this call, I would like to suspend the MainThread and resume it after so that my MainWindow's controls are disabled while the messageBox is shown.

So my questions are:

  • How do I access the mainThread from the backgroundThread?
  • How do I suspend/resume it (Considering Thread.suspend is depricated)?
Chris
  • 8,527
  • 10
  • 34
  • 51
Simon Corcos
  • 962
  • 14
  • 31
  • 3
    There is no point at all in suspending the main thread, MessageBox is already a modal dialog that disables the UI. Simply use Control.Invoke() or Dispatcher.Invoke() in your worker. – Hans Passant Sep 02 '13 at 19:19
  • Ill just suggest events for communication. Dont know about the suspension of thread. – WozzeC Sep 02 '13 at 19:21

1 Answers1

3

Instead of suspending the main thread, you could use Control.Invoke (Windows Forms) or Dispatcher.Invoke (WPF) to actually show the message box on the main thread, but call it from your background thread.

In addition to providing the behavior you wish, this would also have that advantage of allowing you to parent your message box to the proper Window, which would give the proper modal message box behavior.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • Thanks I already knew I could do it like that but I didn't think it would stop the background thread. Why does it? Is it because I started the background thread from the main thread? – Simon Corcos Sep 02 '13 at 19:54
  • @SimonCorcos Using `Invoke` (not `BeginInvoke`) blocks until the delegate completes, which won't happen until you close the message box. – Reed Copsey Sep 02 '13 at 19:56
  • OK thanks a lot for that, it helps me understand multi threading a little more. If I may ask a last question. Why can I only call invoke from Windows form object? Why not from any other objects? And why is it I can't find the System.WindowsBase Assembly (the one with the dispatcher class in it) in my list of references I can I add? (Currently in VS2012 Ultimate) – Simon Corcos Sep 03 '13 at 02:28
  • @SimonCorcos Invoke is a method on Control - (or Dispatcher), so you need to "Invoke" on an object that understands and provides that method. The assembly is just "WindowsBase.dll" (no System). – Reed Copsey Sep 03 '13 at 16:23