TheRRRanger
TheRRRanger

Reputation: 365

Winforms UI unresponsive query

Ive got a UI and within it, a BackgroundWorker.

While the BackgroundWorker is running, it updates the UI by way of Marshalling. During one of the runs, the UI was unresponsive. I hit the pause button in Visual Studio to see what was going on.

The following lines were shown to be running in the Threads window:

  1. Application.Run(new uxRunSetup());

  2. private delegate void DisplayCounterHandler(int[] counts, int total);

    private void DisplayCounter(int[] counts, int total)    
     {  
        if (InvokeRequired)      
       {    
          //stuck on Invoke below.     
          Invoke(new DisplayCounterHandler(DisplayCounter), counts, total);     
                        return;  
       }  
       //some UI updates here.  
    }  
    

Ive been reading through this thread. My question is, lets say the call to DisplayCounterHandler has been made. However, the BackgroundWorker has already completed. Could this cause the UI to be unresponsive and crash?

Thanks.

Upvotes: 3

Views: 401

Answers (1)

debracey
debracey

Reputation: 6607

You should switch your Invoke to a BeginInvoke, ie.

if(this.InvokeRequired)
{
  this.BeginInvoke(...);
  return;
}

// UI updates here

With your invoke line your background worker is forced to wait until the UI opeartions complete, so if some other operation comes along and tries to end the background worker the UI could hang because:

  1. The background worker is waiting on the UI to finish (because of the invoke)
  2. Something on the UI thread has asked the background worker to finish
  3. Since the UI is waiting on the background worker, and the background worker is waiting on the UI, you're hung

So simplest solution is to use BeginInvoke, which will simply "queue up" your UI operations and not stop your background worker from doing its work.

-- Dan

Upvotes: 3

Related Questions