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:
Application.Run(new uxRunSetup());
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 h开发者_StackOverflowere. }
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.
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:
- The background worker is waiting on the UI to finish (because of the invoke)
- Something on the UI thread has asked the background worker to finish
- 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
精彩评论