C# Threads: Jim Fawcett CSE681 - Software Modeling and Analysis Fall 2005
C# Threads: Jim Fawcett CSE681 - Software Modeling and Analysis Fall 2005
Thread Class
Starting C# Threads
Thread States
A thread that has been started, but not yet terminated can be in one of the following states:
Running Waiting to run Suspended Blocked
Thread Properties
Process does not end until all Foreground threads have ended. Background threads are terminated when application ends. Returns thread reference to calling thread Has thread started but not terminated? Highest, AboveNormal, Normal, BelowNormal, Lowest Unstarted, Running, Suspended, Stopped, WaitSleepJoin, ..
IsAlive get
ThreadState get
Sharing Resources
A child thread often needs to communciate with its parent thread. It does this via some shared resource, like a queue.
Parent Thread
Child Thread
Shared Queue Receiving Message from Parent
Synchronization
When two or more threads share a common resource access needs to be serialized - a process called synchronization.
Consider the shared queue on the previous slide. Should the parent start to enqueue an element in an empty queue, but have its time-slice expire before finishing, the queues links are in an undefined state.
Now, if the child thread wakes up, and attempts to dequeue an element the result is undefined.
Demonstration Program
QueuedMessages folder
Illustrates communication between parent and child threads using a queue. Also illustrates use of C# lock operation.
Interlocked Mutex
ArrayList, Hashtable, Queue, Stack, and other collections provide Synchronized() function, supporting high performance locking.
ArrayList unsync = new ArrayList(); ArrayList sync = ArrayList.Synchronized(unsynch);
Method Decoration
Methods can be decorated with a MethodImpl attribute, synchronizing access much like a Win32 critical section.
[MethodImpl (MethodImplOptions.Synchronized)] string myMethod(string input) { }
Note that this synchronizes a region of code, while lock and Monitor synchronize objects.
A UI thread is a thread that creates a window. A worker thread is a thread spawned by a UI thread to do work in the background while the UI thread services UI messages. A worker thread must never access UI functions directly. It accesses them through Forms Invoke, BeginInvoke, and EndInvoke functions, passing a delegate as an argument.
BeginInvoke Example
for (i = 1; i <= 25; i++) { s = "Step number " + i.ToString() + " executed"; Thread.Sleep(400); // Make asynchronous call to main form. // // // // MainForm.AddString function runs in main thread because we activated the delegate through form's Invoke (synchronous) or BeginInvoke (asynchronous) functions. To make synchronous call use Invoke.
m_form.BeginInvoke(m_form.m_DelegateAddString, 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 this thread stopped m_EventStopped.Set(); return; } }
Demonstration Programs
QueuedMessages
Illustrates communication between threads using queues and the C# lock operation.
FormInvokeDemo folder
A more interesting demonstration of the above.
WorkerThread folder
Simple Demonstration of UI and Worker thread communication using Form.Invoke()
ThreadPoolDemo folder
Illustrates how to use the ThreadPool to run functions
End of Presentation