MultiThreaded Form

  • Thread starter Thread starter Ken Saganowski
  • Start date Start date
K

Ken Saganowski

Does anyone have any sample code for a multi threaded form that refreshes
itself while an extended operation is executing:

Example: I am updating a local dataset which could potentially have 1000's
of records. I would like to update a label in the meantime but the problem
is that the form seems to be locked while this operation is executing.

Any advice would be greatly appreciated.
 
Look at the "Safe, Simple Multithreading in Windows Forms" series by Chris
Sells in MSDN.
 
Ken Saganowski said:
Does anyone have any sample code for a multi threaded form that refreshes
itself while an extended operation is executing:

Example: I am updating a local dataset which could potentially have 1000's
of records. I would like to update a label in the meantime but the problem
is that the form seems to be locked while this operation is executing.

Hi Ken,

You can't make calls back onto your UI thread from a secondary thread with
Windows Forms. Instead, need to use Control.Invoke, or one of a couple
other specialized commands that let you marshal the call back to the main UI
thread. Here's the first in a series of three articles that show you how to
do this and why you are having the problems you see now:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnforms/html/winforms06112002.asp

Joe
 
Hi Ken,

I just posted some code to do this, see the thread Re: Progress bar without
GUI code in the model? a few post above your.

IF you have any doubt post back.

Cheers,
 
If you don't need interactivity, stay away from multithreading -- it isn't
necessary. Simply add a call to Refresh() after you update the label text:

Label label;
label.Text = "Processing record " + rec_num.ToString();
label.Refresh();

If you need interactivity w/ your user interface (e.g. you need to allow the
user to cancel the operation mid-stream), you either have to resort to running
the processing in a background thread (i.e. multithreaded) or occasionally
allow messages to be processed (not multi-threaded):


for (/* main processing loop*/)
{
// do one iteration of work

// process any pending messages
// Note: this uses the Win32 api, convert to .NET
while (PeekMessage(..., PM_REMOVE))
{
TranslateMessage(...);
DispatchMessage(...);
}

// break out if user pressed cancel
if (cancel_operation)
{
break;
}
}

Dig?
 
Back
Top