Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


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

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

2 Copyright © 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 © by Dennis A. Fairclough all rights reserved. 3 Thread Usage System.Threading.Thread GUI & Other Apps IO Delegates

4 Running Two Threads Copyright © by Dennis A. Fairclough all rights reserved. 4

5 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()

6 Copyright © 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 exec uted.

7 Copyright © 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

8 Copyright © 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

9 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

10 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

11 Copyright © 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

12 Copyright © 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;

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

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

15 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

16 Copyright © 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 }

17 Copyright © 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)

18 Copyright © 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

19 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 cant obtain the lock Avoids blocking if you cant 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

20 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

21 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

22 enum ThreadState Copyright © by Dennis A. Fairclough all rights reserved. 22 Member nameDescription RunningThe thread has been started, it is not blocked, and there is no pending ThreadAbortException.ThreadAbortException StopRequestedThe thread is being requested to stop. This is for internal use only. SuspendRequestedThe 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.Thread..::.IsBackground UnstartedThe Thread..::.Start method has not been invoked on the thread.Thread..::.Start StoppedThe 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.Thread..::.SleepThread..::.JoinMonitor..::.EnterMonitor..::.WaitManualResetEvent SuspendedThe 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.Thread..::.AbortSystem.Threading..::.ThreadAbortException Aborted The thread state includes AbortRequested and the thread is now dead, but its state has not yet changed to Stopped. Members

23 Actions Changing Thread State Copyright © by Dennis A. Fairclough all rights reserved. 23 ActionThreadState A thread is created within the common language runtime.Unstarted A thread calls StartStartUnstarted The thread starts running.Running The thread calls SleepSleepWaitSleepJoin The thread calls Wait on another object.WaitWaitSleepJoin The thread calls Join on another thread.JoinWaitSleepJoin Another thread calls InterruptInterruptRunning Another thread calls SuspendSuspendSuspendRequested The thread responds to a Suspend request.SuspendSuspended Another thread calls ResumeResumeRunning Another thread calls AbortAbortAbortRequested The thread responds to a Abort request.AbortStopped A thread is terminated.Stopped The following table shows the actions that cause a change of state.

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

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

26 Threading GUIs & Apps See Example Code Copyright © by Dennis A. Fairclough all rights reserved. 26

27 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. 27

28 Copyright © 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)

29 Copyright © 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

30 Copyright © 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)

31 Copyright © 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

32 Copyright © 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 didnt actually spawn a thread Use with IO operations IsCompleted Indicates whether the operation has completed AsyncResult object extend if you need specialized behavior

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. 33

34 Copyright © 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)

35 Copyright © 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

36 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

37 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)

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


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

Similar presentations


Ads by Google