Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# Threading & Timers C#.NET Software Development Version 1.0.

Similar presentations


Presentation on theme: "C# Threading & Timers C#.NET Software Development Version 1.0."— Presentation transcript:

1 C# Threading & Timers C#.NET Software Development Version 1.0

2 Copyright © 2006-2008 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 Main Thread (Primary Thread) Child Thread (Worker Thread)

3 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 3 Thread Usage  System.Threading.Thread  GUI & Other Apps  IO  Delegates

4 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 4 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()

5 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 5 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

6 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 6 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

7 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 7 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

8 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 8 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

9 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 9 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

10 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 10 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

11 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 11 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;

12 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 12 Apartment Threading (C# Help) Member name Description MTAThe Thread will create and enter a multithreaded apartment. STAThe Thread will create and enter a single-threaded apartment. UnknownThe ApartmentState property has not been set. Members Remarks An 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. ApartmentState

13 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 13 Race Conditions  Covered thoroughly in CNS 3060  Solved using a Mutex, Semaphore or Monitor Called Synchronization

14 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 14 Synchronization Classes and Constructs  lock keyword  Mutex class  Monitor class  Interlocked class  ReaderWriterLock class

15 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 15 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 }

16 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 16 The lock Monitor  lock defines one Monitor for each object locked on  Blocks until the current thread is finished (See Lock Demo)

17 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 17 Mutex Class  Stands for Mutual-Exclusion  Blocking synchronization object  WaitOne() Begins the critical section  ReleaseMutex() Ends critical section Call ReleaseMutex() in a finally block

18 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 18 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

19 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 19 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

20 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 20 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

21 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 21 Deadlock  Your job to avoid it object1 object2 Resource1 has waiting for

22 Threading GUI’s & Apps  See Example Code Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 22

23 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 23 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)

24 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 24 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

25 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 25 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)

26 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 26 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

27 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 27 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

28 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-2008 by Dennis A. Fairclough all rights reserved. 28

29 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 29 Timers  Timers execute a method at a given interval  Three to choose from: System.Timers.Timer System.Threading.Timer System.Windows.Forms.Timer

30 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 30 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

31 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 31 System.Threading.Timer  Constructor: Timer(TimerCallBack, object, long, long)  Members: Change(long, long)  TimerCallBack System.Threading.TimerCallBack(object state) cannot be changed once set

32 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 32 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)

33 Copyright © 2006-2008 by Dennis A. Fairclough all rights reserved. 33 What did you learn?  ??


Download ppt "C# Threading & Timers C#.NET Software Development Version 1.0."

Similar presentations


Ads by Google