Presentation is loading. Please wait.

Presentation is loading. Please wait.

C# .NET Software Development Version 1.1

Similar presentations


Presentation on theme: "C# .NET Software Development Version 1.1"— Presentation transcript:

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

2 Threading: Advantages and Dangers
Main Thread (Primary Thread) Reasons to use Threading UI Responsiveness Timers Multiple processors Dangers Race Conditions Deadlock Child Thread (Worker Thread) Copyright © by Dennis A. Fairclough all rights reserved.

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

4 Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved.
Running Two Threads Copyright © 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 © by Dennis A. Fairclough all rights reserved.

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

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

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

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

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

14 Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved.
Race Conditions Covered thoroughly in CNS 3060 Solved using a Mutex, Semaphore or Monitor Called Synchronization Copyright © 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 © by Dennis A. Fairclough all rights reserved.

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

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

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

22 Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved.
Members enum ThreadState 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. Background The 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. WaitSleepJoin The 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. AbortRequested The 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. Copyright © by Dennis A. Fairclough all rights reserved.

23 Actions Changing Thread State
The following table shows the actions that cause a change of state. Actions Changing Thread State Action ThreadState A thread is created within the common language runtime. Unstarted A thread calls Start The thread starts running. Running The thread calls Sleep WaitSleepJoin The thread calls Wait on another object. The thread calls Join on another thread. Another thread calls Interrupt Another thread calls Suspend SuspendRequested The thread responds to a Suspend request. Suspended Another thread calls Resume Another thread calls Abort AbortRequested The thread responds to a Abort request. Stopped A thread is terminated. Copyright © by Dennis A. Fairclough all rights reserved.

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

25 Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved.
ReadyWait Copyright © by Dennis A. Fairclough all rights reserved.

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

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

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

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

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

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

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

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

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

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

38 Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved.
What did you learn? ?? Copyright © by Dennis A. Fairclough all rights reserved.


Download ppt "C# .NET Software Development Version 1.1"

Similar presentations


Ads by Google