Alex F January 29, 2002
Environment: Visual Studio .NET Beta 2, Windows 2000 SP2
.NET framework allows a lot of ways to implement multithreading program. I want to show how we can run worker thread which makes synchronous calls to user interface (for example, thread reads a long recordset and fills some control in the form). (Continued )
To Run Thread I Use:
THREAD INSTANTS Used to Stop Thread. First Event is set by the main thread wants to stop...............
.NET allows to call System.Windows.Forms.Control functions only from thread where control was created. To run them from other thread we need to use Control.Invoke (synchronous call) or Control.BeginInvoke (asynchronous call) functions. For task Like Showing Database Records We Need Invoke. TO IMPLEMENT THIS i Use:
Delegate Type for calling form function, delegate instance and function caled sale this delegate Invoke Call from worker thread.
Next problem is to stop worker thread correvently. Steps to do this:
Set event "Stop Thread" Wait for event "Thread is stopped" While waiting for event process messages using Application.DoEvents function. This prevents deadlock because worker thread makes Invoke calls which are processed in main thread.
Thread Function Checks in Every Item WHETER STOP THREAD EVENT IS SET. IF Event IS Set, Function Makes Clean-Up Operations, Sets Event "Thread is Stopped" and returns.
Demo project has two classes:. MainForm and LongProcess LongProcess.Run function runs in thread and fills list box with some lines Worker thread may finish by natural awy or may be stopped when user presses Stop Thread button or closes form.Code fragments.:
// mainform.cs
Namespace workerthread
{
// delegates Used to Call Mainform Functions from
// Worker Thread
Public delegate void delegateAddString (String s);
Public delegate void delegatethreadfinished ();
Public Class Mainform: System.Windows.Forms.form
{
...
// Worker Thread
Thread m_workerthread;
// Events Used to Stop Worker Thread
ManualRevent M_EventStopthread;
ManualReveTevent M_EventthreadStopped;
// delegate instances use to call user interface
// functions from worker thread:
Public delegateAddstring m_dlegateaddstring;
Public DelegateThreadFinished M_DelegateThreadFinished;
...
Public mainform ()
{
InitializationComponent ();
// Initialize Delegates
m_dlegateaddstring =
New delegateAddstring (this.addstring);
m_delegatethreadfinished =
New delegateThreadFinished (this.threadfinished);
// Initialize Events
M_EventStopthread = New ManualReset (false);
M_EventthreadStopped = New ManualReveTevent (false);
}
...
// Start Thread Button IS PRESSED
Private void btnstartthread_click (Object Sender,
System.Eventargs E)
{
...
// RESET EVENTS
M_EventStopthread.reset ();
m_EventthreadStopped.reset ();
// Create Worker Thread Instance
m_WorkerthRead =
New Thread (New ThreadStart (this.WorkerthReadFunction);
M_WorkerthRead.name = "worker thread sample"; // looks nice
// in Output WINDOW
m_WorkerthRead.start ();
}
// worker thread function.
// Called Indirectly from btnstartthread_click
Private void workerthreadfunction () {
Longprocess longprocess;
Longprocess = new longprocess (m_eventstopthread,
M_EventthreadStopped, this);
Longprocess.run ();
}
// Stop Worker Thread if it is running.
// Called WHEN User Presses Stop Button or Form is Closed.
Private void stopthread ()
{
IF (M_WorkerthRead! = NULL &&
m_workerthread.isalive) // Thread is Active
{
// set event "stop"
m_EventStopthread.set ();
// Wait When Thread Will Stop Or Finish
While (M_WorkerthRead.isalive)
{
// We cannot USE Here Infinite Wait Becauseur Thread
// Makes Syncronous Calls to Main Form, this Will Cause
// deadlock.
// instead of this we wait for Event Some ApproPriate Time
// (and by the way give time to worker thread) and
// Process Events. Thase Events May Contain Invoke Calls.
IF (WaitHandle.waitall)
(New ManualReveTevent [] {m_everThreadStopped},
100,
True))
{
Break;
}
Application.doevents ();
}
}
}
// Add string to list box.
// Called from worker thread usding delegate and control.invoke
Private void addstring (String S)
{
ListBox1.Items.Add (s);
}
// set initial state of controls.
// Called from worker thread usding delegate and control.invoke
Private void threadfinished ()
{
BtnStartthread.enabled = true;
BtnStopthread.enabled = false;
}
}
}
// longprocess.cs
Namespace workerthread
{
Public class longprocess
{
...
// Function Runs in worker thread and emulates long process.
Public void Run ()
{
INT I;
String S;
For (i = 1; i <= 10; i )
{
// Make Step
S = "step number" i.toString () "executed";
Thread.sleep (400);
// make synchronous call to main form.
// mainform.addstring function runs in main thread.// to make ask inynchronous call users
m_form.invoke (m_form.m_dlegateaddstring, new object [] {s});
// Check if thread is cancelled
IF (M_EventStop.waitone (0, True))
{
// Clean-Up Operations May Be Placed Here
// ...
// Inform Main Thread That Thread Stopped
m_EventStopped.set ();
Return;
}
}
// Make asynchronous call to main form
// TO Inform It That Thread Finished
m_form.invoke (m_form.m_delegatethreadfinished, null);
}
}
}
Downloads
Download Demo Project - 8 KB