c# threading & timers c#.net software development version 1.1
TRANSCRIPT
C# Threading & Timers
C# .NET Software Development
Version 1.1
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 2
Threading: Advantages and Dangers Reasons to use Threading
UI Responsiveness Timers Multiple processors
Dangers Race Conditions Deadlock
MainThread
(Primary Thread)
ChildThread
(Worker Thread)
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 3
Thread Usage
System.Threading.Thread GUI & Other Apps IO Delegates
Running Two Threads
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 4
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 5
System.Threading.Thread
For more control over your threading situation Members:
static CurrentThread static Sleep() Constructor
Thread(ThreadStart start) IsBackground Priority ThreadState Abort() Interrupt() Join() Resume() Start() Suspend()
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 6
Thread Static Members CurrentThread
Returns a thread object for the current thread Sleep(int ticks)
1 tick == 1 ms Sleep(0) just releases the CPU Never use a busy-wait
Thread.Sleep (TimeSpan.FromHours (1)); // sleep for 1 hour
Thread.Sleep (500); // sleep for 500 milliseconds Thread.Sleep (0); // relinquish CPU time-slice
Thread.Sleep(0) relinquishes the processor just long enough to allow any other active threads present in a time-slicing queue (should there be one) to be
executed.
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 7
Thread Properties
IsBackground get or set Once all foreground threads are finished, the runtime calls Abort on
all background threads Default is false (or foreground)
Priority ThreadPriority Enum Lowest, BelowNormal, Normal, AboveNormal, Highest
ThreadState New Thread: ThreadState.Unstarted Started Thread: ThreadState.Running Sleep called: ThreadState.WaitSleepJoin Suspend called: ThreadState.Suspended See ThreadState Enumeration
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 8
Thread Methods Start()
Begins execution of the thread Once a thread is finished, it cannot be restarted
Suspend() Suspends the thread If the thread is already suspended, there is no effect
Resume() Resumes a suspended thread
Interrupt() Resumes a thread that is in a WaitSleepJoin state If the thread is not in WaitSleepJoin state it will be interrupted next time it is
blocked
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 9
Thread Methods (Continued) Abort()
Attempts to abort the thread Throws a ThreadAbortException Usually bad results occur
Join() Blocks the calling thread until the owning thread
terminates
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 10
Exceptions Between threads Exceptions must be handled in the thread they were
thrown in Exceptions not handled in a thread are considered
unhandled and will terminate that thread
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 11
Threading Dangers volatile Fields
The CPU often stores variables in registers for optimization Other threads accessing that variable may not get the true
value
Race Conditions When multiple threads access the same memory A thread is interrupted while updating memory Solution: “lock” memory in a mutex, monitor, etc.
Deadlock Two or more threads waiting on each others resources to be
released
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 12
volatile Fields
volatile fields may not be cached Types that may be volatile are:
Any reference type Any pointer (unsafe code) sbyte, byte, short, ushort, int, uint An enum with one of the above base types
Example:
The Thread class also contains 2 static methods: VolatileRead() VolatileWrite()
public volatile int myChangingInt = 0;
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 13
Apartment Threading(C# Help)
Member name
Description
MTA The Thread will create and enter a multithreaded apartment.
STA The Thread will create and enter a single-threaded apartment.
Unknown The ApartmentState property has not been set.
Members
RemarksAn apartment is a logical container within a process for objects sharing the same thread access requirements. All objects in the same apartment can receive calls from any thread in the apartment. The .NET Framework does not use apartments, and managed objects are responsible for using all shared resources in a thread-safe manner themselves.
Because COM classes use apartments, the common language runtime needs to create and initialize an apartment when calling a COM object in a COM interop situation. A managed thread can create and enter a single-threaded apartment (STA) that allows only one thread, or a multithreaded apartment (MTA) that contains one or more threads. You can control the type of apartment created by setting the ApartmentState property of the thread to one of the values of the ApartmentState enumeration. Because a given thread can only initialize a COM apartment once, you cannot change the apartment type after the first call to the unmanaged code.
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 14
Race Conditions
Covered thoroughly in CNS 3060 Solved using a Mutex, Semaphore or
Monitor Called Synchronization
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 15
Synchronization Classes and Constructs
lock keyword Mutex class Monitor class Semaphore class Interlocked class Barrier class WaitHandle ReaderWriterLock class Thread ThreadPool Timer
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 16
The lock Keyword
Marks a statement as a critical section Is a Monitor underneath Example:
lockObject must be a reference-type instance Typically you will lock on:
‘this’ locks the current instance
typeof(MyClass) global lock for the given type
A collection instance locks access to a specific collection
lock(lockObject){ // critical section}
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 17
The lock Monitor lock defines one Monitor for each object locked on
Blocks until the current thread is finished
(See Lock Demo)
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 18
Mutex Class Stands for Mutual-Exclusion
Blocking synchronization object
WaitOne() Begins the critical section
ReleaseMutex() Ends critical section Call ReleaseMutex() in a finally block
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 19
Monitor Class (static) Enter(object obj)
Begins a critical section Blocks if another thread has the same lock
Exit(object obj) Ends a critical section Releases the lock
TryEnter(object obj) Returns true if it obtains the lock Returns false if it can’t obtain the lock Avoids blocking if you can’t obtain the lock
Wait(object obj) Releases the lock on an object and blocks until it reaquires the lock
Pulse(object obj) Signals the next waiting thread that the lock may be free
PulseAll(object obj) Signals all waiting threads that the lock may be free
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 20
Interlocked Class (static) Provides atomic operations for variables CompareExchange(ref int dest, int source, int compare)
Replaces dest with source if dest == compare Overloaded
Exchange(ref int dest, int source) places source into dest returns the original value of dest
Increment(ref int value) increments value
Decrement(ref int value) decrements value
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 21
ReaderWriterLock Class
Allows a single writer or multiple readers Members:
IsReaderLockHeld IsWriterLockHeld WriterSeqNum AcquireReaderLock()
Increments the reader count AcquireWriterLock()
Blocks until the lock is obtained ReleaseReaderLock()
Decrements the reader count ReleaseWriterLock()
Releases the writer lock ReleaseLock()
Unconditionally releases the lock
enum ThreadState
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 22
Member name Description
Running The thread has been started, it is not blocked, and there is no pending ThreadAbortException.
StopRequested The thread is being requested to stop. This is for internal use only.
SuspendRequested The thread is being requested to suspend.
BackgroundThe thread is being executed as a background thread, as opposed to a foreground thread. This state is controlled by setting the Thread..::.IsBackground property.
Unstarted The Thread..::.Start method has not been invoked on the thread.
Stopped The thread has stopped.
WaitSleepJoinThe thread is blocked. This could be the result of calling Thread..::.Sleep or Thread..::.Join, of requesting a lock — for example, by calling Monitor..::.Enter or Monitor..::.Wait — or of waiting on a thread synchronization object such as ManualResetEvent.
Suspended The thread has been suspended.
AbortRequestedThe Thread..::.Abort method has been invoked on the thread, but the thread has not yet received the pending System.Threading..::.ThreadAbortException that will attempt to terminate it.
Aborted The thread state includes AbortRequested and the thread is now dead, but its state has not yet changed to Stopped.
Members
Actions Changing Thread State
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 23
Action ThreadState
A thread is created within the common language runtime. Unstarted
A thread calls Start Unstarted
The thread starts running. Running
The thread calls Sleep WaitSleepJoin
The thread calls Wait on another object. WaitSleepJoin
The thread calls Join on another thread. WaitSleepJoin
Another thread calls Interrupt Running
Another thread calls Suspend SuspendRequested
The thread responds to a Suspend request. Suspended
Another thread calls Resume Running
Another thread calls Abort AbortRequested
The thread responds to a Abort request. Stopped
A thread is terminated. Stopped
The following table shows the actions that cause a change of state.
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 24
Deadlock
Your job to avoid it
object1
object2
Resource1Resource1
has
has
waiting for
waiting for
ReadyWait
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 25
Threading GUI’s & Apps
See Example Code
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 26
UI Threading 19.6.3. Thread Safety in Rich Client Applications Both the Windows Forms and Windows Presentation Foundation (WPF) libraries have
special threading models. Although each has a separate implementation, they are both very similar in how they function.
The objects that make up a rich client are primarily based on Control in the case of Windows Forms or DependencyObject in the case of WPF. None of these objects is thread-safe, and so cannot be safely accessed from two threads at once. To ensure that you obey this, WPF and Windows Forms have models whereby only the thread that instantiates a UI object can call any of its members. Violate this and an exception is thrown.
On the positive side, this means you don't need to lock around accessing a UI object. On the negative side, if you want to call a member on object X created on another thread Y, you must marshal the request to thread Y. You can do this explicitly as follows:
In Windows Forms, call Invoke or BeginInvoke on the control. In WPF, call Invoke or BeginInvoke on the element's Dispatcher object. Invoke and BeginInvoke both accept a delegate, which references the method on the
target control that you want to run. Invoke works synchronously: the caller blocks until the marshal is complete. BeginInvoke works asynchronously: the caller returns immediately and the marshaled request is queued up (using the same message queue that handles keyboard, mouse, and timer events).
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 27
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 28
Windows Threading Primary Thread
Worker Threads Windows disallows updating many GUI components
across threads To update from the worker thread to the GUI thread
InvokeRequired Invoke(System.Delegate)
(See Invoke Demo)
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 29
Threading IO ASyncCallBack
FileStream.BeginRead(byte[] buffer, int offset, int numBytes, ASyncCallBack userCallBack, object stateObject)
returns IAsyncResult object
userCallBack delegate void ASyncCallBack(IAsyncResult ar) gets executed when the operation is finished
FileStream.EndRead(IAsyncResult ar) Waits (blocks until the read is complete) returns (int) the number of bytes read
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 30
Threading a Delegate BeginInvoke(AsyncCallBack userCallBack, object stateObject)
Returns an IAsyncResult object executes userCallBack when finished
EndInvoke(IAsyncResult ar) Blocks until the delegate thread is finished
Use AsyncResult object unless you have specific needs
(See DelegateThreading Demo)
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 31
Thread Constructor Takes a ThreadStart delegate
ThreadStart(void () target) Takes a method which returns void and has no
params: void MyMethod()
Thread begins execution when Start() is called Thread executes method passed to ThreadStart
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 32
IAsyncResult
Members: AsyncState
User Object passed in AsynchWaitHandle
Gets a thread handle that can be used to block CompletedSynchronously
Indicates that the operation was fast enough that the system didn’t actually spawn a thread
Use with IO operations IsCompleted
Indicates whether the operation has completed
AsyncResult object extend if you need specialized behavior
C# Thread Pools (C# help) A thread pool is a collection of threads that can be used to perform
several tasks in the background (background threads). This leaves the primary thread free to perform other tasks asynchronously.
Thread pools are often employed in server applications. Each incoming request is assigned to a thread from the thread pool, so that the request can be processed asynchronously, without tying up the primary thread or delaying the processing of subsequent requests.
Once a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. This reuse enables applications to avoid the cost of creating a new thread for each task.
Thread pools typically have a maximum number of threads. If all the threads are busy, additional tasks are put in queue until they can be serviced as threads become available.
See Example code in C# Help.
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 33
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 34
Timers Timers execute a method at a given interval
Three to choose from: System.Timers.Timer System.Threading.Timer
The other two are special-purpose single-threaded timers: System.Windows.Forms.Timer (Windows Forms timer) System.Windows.Threading.DispatcherTimer (WPF timer)
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 35
System.Timers.Timer Constructors:
Timer() Timer(double interval)
Members: bool AutoReset bool Enabled double Interval
in milliseconds (ms) Close() Start() Stop() Elapsed
System.Timers.ElapsedEventHandler delegate
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 36
System.Threading.Timer Constructor:
Timer(TimerCallBack, object, long, long) Members:
Change(long, long)
TimerCallBack System.Threading.TimerCallBack(object state) cannot be changed once set
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 37
System.Windows.Forms.Timer
Has to be used with Windows Forms Members:
bool Enabled int Interval Start() Stop() Tick
System.EventHandler delegate
(See Timers Demo)
Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. 38
What did you learn?
??