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

Slides:



Advertisements
Similar presentations

Advertisements

How to Build Multi- threaded Applications in.NET Mazen S. Alzogbi Technology Specialist Microsoft Corporation.
C# .NET Software Development Version 1.1
Ch 7 B.
Lecture 5 Concurrency and Process/Thread Synchronization     Mutual Exclusion         Dekker's Algorithm         Lamport's Bakery Algorithm.
Chapter 6: Process Synchronization
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 6: Process Synchronization.
Process Synchronization. Module 6: Process Synchronization Background The Critical-Section Problem Peterson’s Solution Synchronization Hardware Semaphores.
CH7 discussion-review Mahmoud Alhabbash. Q1 What is a Race Condition? How could we prevent that? – Race condition is the situation where several processes.
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#.
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.
1 Threads CSCE 351: Operating System Kernels Witawas Srisa-an Chapter 4-5.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L19 (Chapter 24) Multithreading.
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.
Race Conditions CS550 Operating Systems. Review So far, we have discussed Processes and Threads and talked about multithreading and MPI processes by example.
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
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
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
Threads in Java. History  Process is a program in execution  Has stack/heap memory  Has a program counter  Multiuser operating systems since the sixties.
Multi-Threaded Application CSNB534 Asma Shakil. Overview Software applications employ a strategy called multi- threaded programming to split tasks into.
MODERN OPERATING SYSTEMS Third Edition ANDREW S. TANENBAUM Chapter 2 Processes and Threads Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall,
Java Threads 11 Threading and Concurrent Programming in Java Introduction and Definitions D.W. Denbo Introduction and Definitions D.W. Denbo.
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
1.NETConcurrent programmingNOEA / PQC 2007 Concurrent programming Threads –Introduction –Synchronization.
Internet Software Development Controlling Threads Paul J Krause.
Concurrency: Mutual Exclusion and Synchronization Chapter 5.
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.
In Java processes are called threads. Additional threads are associated with objects. An application is associated with an initial thread via a static.
Java Thread and Memory Model
Threads Doing Several Things at Once. Threads n What are Threads? n Two Ways to Obtain a New Thread n The Lifecycle of a Thread n Four Kinds of Thread.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Concurrency & Dynamic Programming.
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.
Concurrency (Threads) Threads allow you to do tasks in parallel. In an unthreaded program, you code is executed procedurally from start to finish. In a.
CIS NET Applications1 Chapter 8 – Multithreading and Concurrency Management.
Mutual Exclusion -- Addendum. Mutual Exclusion in Critical Sections.
Concurrent Programming in Java Based on Notes by J. Johns (based on Java in a Nutshell, Learning Java) Also Java Tutorial, Concurrent Programming in Java.
Java Thread Programming
Segments Introduction: slides minutes
Multithreading / Concurrency
Threading Lecture 11 M. Ipalakova.
Multi Threading.
Multithreading.
Background on the need for Synchronization
Jim Fawcett CSE681 – Software Modeling & Analysis Fall 2002
Thread Fundamentals Header Advanced .NET Threading, Part 1
Jim Fawcett CSE681 – Software Modeling and Analysis Fall 2005
MODERN OPERATING SYSTEMS Third Edition ANDREW S
Multithreading.
Multithreading.
Threading using C# and .Net
Multithreaded Programming
Chapter 7: Synchronization Examples
Multithread Programming
Conditions for Deadlock
Threads and Multithreading
CSE 451 Section 1/27/2000.
CSE 542: Operating Systems
CSE 542: Operating Systems
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

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

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)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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