Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program hanging on Dispatcher.Run() c#

I'm using this code to run ProgressBar in separate thread.

ProgresBarForm viewer = new ProgressBarForm("Wait");    
Thread viewerThread = new Thread(delegate()
    {
        viewer = new ProgressBarForm("Wait");
        viewer.Show();
        System.Windows.Threading.Dispatcher.Run();
    });

viewerThread.SetApartmentState(ApartmentState.STA); // needs to be STA or throws exception
viewerThread.Start();

Then i'm doing some long operation and when i finish i'm invoking this code:

viewer.BeginInvoke(new Action(() => window.Close()));

and it works really well but when I close my window debugger is not stopping. In VS 2012 I click "Break All" button and it occurs that program is hanging on line

System.Windows.Threading.Dispatcher.Run();

How can I close this dispatcher to exit from my program?

Thanks in advance for all responses.

like image 809
DinosaurTom Avatar asked Dec 15 '22 18:12

DinosaurTom


1 Answers

   viewer.BeginInvoke(new Action(() => window.Close()));

That isn't good enough to get the dispatcher to stop. Your "viewer" is a Winforms Form, not a WPF window. So the normal shutdown mechanism can't work. You have to help and also tell the dispatcher to quit:

   viewer.BeginInvoke(new Action(() => {
       System.Windows.Threading.Dispatcher.CurrentDispatcher.InvokeShutdown();
       viewer.Close();
   }));

Do beware the race, the user might close your WPF window before you get a chance to call this code. Visions of DoEvents() misery abound. So you probably should also set the thread's IsBackground property to true. And do beware the problems with displaying UI on a worker thread, you have to carefully craft your "progress" form so it doesn't use any of the dangerous controls in the toolbox. The ones that use the SystemEvents class. Or you get to debug a deadlock like this.

This forever works better and more reliably if you do not let your UI thread do the heavy work. Let it take care of just the UI, do the heavy lifting in a worker thread.

like image 138
Hans Passant Avatar answered Jan 02 '23 21:01

Hans Passant