C# .NET Software Development Version 1.1

Slides:



Advertisements
Similar presentations
Shared-Memory Model and Threads Intel Software College Introduction to Parallel Programming – Part 2.
Advertisements

Module 6: Process Synchronization
Process Description and Control
1 Concurrency: Deadlock and Starvation Chapter 6.
Chapter 7 Constructors and Other Tools. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 7-2 Learning Objectives Constructors Definitions.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 12 Introduction to ASP.NET.
Copyright © 2011, Elsevier Inc. All rights reserved. Chapter 6 Author: Julia Richards and R. Scott Hawley.
Author: Julia Richards and R. Scott Hawley
1 Copyright © 2013 Elsevier Inc. All rights reserved. Chapter 3 CPUs.
UNITED NATIONS Shipment Details Report – January 2006.
© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of Chapter 5: Repetition and Loop Statements Problem Solving & Program.
1 Processes and Threads Creation and Termination States Usage Implementations.
1 Interprocess Communication 1. Ways of passing information 2. Guarded critical activities (e.g. updating shared data) 3. Proper sequencing in case of.
How to Build Multi- threaded Applications in.NET Mazen S. Alzogbi Technology Specialist Microsoft Corporation.
Outline Introduction Assumptions and notations
Operating Systems: Monitors 1 Monitors (C.A.R. Hoare) higher level construct than semaphores a package of grouped procedures, variables and data i.e. object.
Ken Birman 1. Refresher: Dekers Algorithm Assumes two threads, numbered 0 and 1 CSEnter(int i) { int J = i^1; inside[i] = true; turn = J; while(inside[J]
Lilian Blot VARIABLE SCOPE EXCEPTIONS FINAL WORD Final Lecture Spring 2014 TPOP 1.
1 Processes and Threads Chapter Processes 2.2 Threads 2.3 Interprocess communication 2.4 Classical IPC problems 2.5 Scheduling.
1 of 31 Images from Africa. 2 of 31 My little Haitian friend Antoine (1985)
1 of 32 Images from Africa. 2 of 32 My little Haitian friend Antoine (1985)
PSSA Preparation.
Essential Cell Biology
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 13 - Exception Handling Outline 13.1 Introduction 13.2 Exception-Handling Overview 13.3 Other.
Chapter 9: Using Classes and Objects. Understanding Class Concepts Types of classes – Classes that are only application programs with a Main() method.
Ch 7 B.
Lecture 5 Concurrency and Process/Thread Synchronization     Mutual Exclusion         Dekker's Algorithm         Lamport's Bakery Algorithm.
Chapter 6: Process Synchronization
Chapter 14 Multithreading Yingcai Xiao. Multithreading is a mechanism for performing two or more tasks concurrently.  In the managed world of the common.
Threads in C# Threads in C#.
C# Threading & Timers C#.NET Software Development Version 1.0.
Threading Part 2 CS221 – 4/22/09. Where We Left Off Simple Threads Program: – Start a worker thread from the Main thread – Worker thread prints messages.
5.6 Semaphores Semaphores –Software construct that can be used to enforce mutual exclusion –Contains a protected variable Can be accessed only via wait.
Concurrency: Mutual Exclusion, Synchronization, Deadlock, and Starvation in Representative Operating Systems.
 2006 Pearson Education, Inc. All rights reserved Multithreading.
Parallel Processing (CS526) Spring 2012(Week 8).  Thread Status.  Synchronization in Shared Memory Programming(Java threads ) ◦ Locks ◦ Barriars.
Windows Programming Using C# Threading. 2 Contents Threading Thread class Interlocked class Monitor class Semaphore class Thread Pools.
Object Oriented Analysis & Design SDL Threads. Contents 2  Processes  Thread Concepts  Creating threads  Critical sections  Synchronizing threads.
Overview of Threading with the.NET Framework  Wallace B. McClure  Scalable Development, Inc. Scalable Development, Inc. Building systems today that perform.
MultiThreading in.NET 2.0 Neal S. Buchalter NSB Consulting
CNS 3260 C# .NET Software Development
MODERN OPERATING SYSTEMS Third Edition ANDREW S. TANENBAUM Chapter 2 Processes and Threads Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall,
111 © 2002, Cisco Systems, Inc. All rights reserved.
1 Program5 Due Friday, March Prog4 user_thread... amount = … invoke delegate transact (amount)... mainThread... Total + = amount … user_thread...
Upcoming Presentations ILM Professional Service – Proprietary and Confidential ( DateTimeTopicPresenter March PM Distributed.
Java Thread and Memory Model
1 Prog4 user_thread... amount = … invoke delegate transact (amount)... mainThread... Total + = amount … user_thread... amount = … invoke delegate transact.
13-1 Chapter 13 Concurrency Topics Introduction Introduction to Subprogram-Level Concurrency Semaphores Monitors Message Passing Java Threads C# Threads.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
4.1 Introduction to Threads Overview Multithreading Models Thread Libraries Threading Issues Operating System Examples Windows XP Threads Linux Threads.
CIS NET Applications1 Chapter 8 – Multithreading and Concurrency Management.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
© Janice Regan, CMPT 300, May CMPT 300 Introduction to Operating Systems Mutual Exclusion Mutexes, Semaphores.
Segments Introduction: slides minutes
Multithreading / Concurrency
Threading Lecture 11 M. Ipalakova.
Multi Threading.
Background on the need for Synchronization
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2002
Thread Fundamentals Header Advanced .NET Threading, Part 1
Other Important Synchronization Primitives
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
MODERN OPERATING SYSTEMS Third Edition ANDREW S
Multithreading.
Threading using C# and .Net
Multithreaded Programming
Multithread Programming
Threads and Multithreading
CSE 451 Section 1/27/2000.
CSE 542: Operating Systems
Presentation transcript:

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

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

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

Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved. Running Two Threads Copyright © 2006-2011 by Dennis A. Fairclough all rights reserved.

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.

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

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

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

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.

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.

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

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

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

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

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.

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

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

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

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.

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.

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

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

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

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

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

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

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

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

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

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

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

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

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.

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

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

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.

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.

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