CNS 3260 C# .NET Software Development

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.
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.
CS 5704 Fall 00 1 Monitors in Java Model and Examples.
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.
Thread Control methods The thread class contains the methods for controlling threads Thread() create default thread Thread(target: runnable ) creates new.
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.
Instructor: Umar KalimNUST Institute of Information Technology Operating Systems Process Synchronization.
1 Concurrency: Deadlock and Starvation Chapter 6.
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.
MultiThreading in.NET 2.0 Neal S. Buchalter NSB Consulting
Threads. Overview Problem Multiple tasks for computer Draw & display images on screen Check keyboard & mouse input Send & receive data on network Read.
The University of Adelaide, School of Computer Science
111 © 2002, Cisco Systems, Inc. All rights reserved.
Practical OOP using Java Basis Faqueer Tanvir Ahmed, 08 Jan 2012.
1 Confidential Enterprise Solutions Group Process and Threads.
1.NETConcurrent programmingNOEA / PQC 2007 Concurrent programming Threads –Introduction –Synchronization.
Synchronized and Monitors. synchronized is a Java keyword to denote a block of code which must be executed atomically (uninterrupted). It can be applied.
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.
Li Tak Sing COMPS311F. Threads A thread is a single sequential flow of control within a program. Many programming languages only allow you to write programs.
Concurrency Control 1 Fall 2014 CS7020: Game Design and Development.
CHARLES UNIVERSITY IN PRAGUE faculty of mathematics and physics Advanced.NET Programming I 5 th Lecture Pavel Ježek
Monitors and Blocking Synchronization Dalia Cohn Alperovich Based on “The Art of Multiprocessor Programming” by Herlihy & Shavit, chapter 8.
1 Prog4 user_thread... amount = … invoke delegate transact (amount)... mainThread... Total + = amount … user_thread... amount = … invoke delegate transact.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 More on Thread API.
CS533 – Spring Jeanie M. Schwenk Experiences and Processes and Monitors with Mesa What is Mesa? “Mesa is a strongly typed, block structured programming.
Thread A thread represents an independent module of an application that can be concurrently execution With other modules of the application. MULTITHREADING.
CIS NET Applications1 Chapter 8 – Multithreading and Concurrency Management.
Concurrency in Java MD. ANISUR RAHMAN. slide 2 Concurrency  Multiprogramming  Single processor runs several programs at the same time  Each program.
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
Advanced .NET Programming I 11th Lecture
Multithreading / Concurrency
Threading Lecture 11 M. Ipalakova.
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
Multithreading.
Multithreading.
Threading using C# and .Net
Multithreaded Programming
Critical section problem
Chapter 7: Synchronization Examples
Multithread Programming
Threads and Multithreading
Foundations and Definitions
Multithreading Dr. John P. Abraham.
CSE 153 Design of Operating Systems Winter 2019
CSE 542: Operating Systems
CSE 542: Operating Systems
Java Chapter 3 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

CNS 3260 C# .NET Software Development C# Threading CNS 3260 C# .NET Software Development C# Threading

Timers Timers execute a method at a given interval Three to choose from: System.Timers.Timer System.Threading.Timer System.Windows.Forms.Timer C# Threading

System.Timers.Timer Constructors: Members: Timer() Timer(double interval) Members: bool AutoReset bool Enabled double Interval in milliseconds Close() Start() Stop() Elapsed System.Timers.ElapsedEventHandler delegate C# Threading

System.Threading.Timer Constructor: Timer(TimerCallBack, object, long, long) Members: Change(long, long) TimerCallBack System.Threading.TimerCallBack(object state) cannot be changed once set C# Threading

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) C# Threading

Threading: Advantages and Dangers Main Thread Reasons to use Threading Timers UI Responsiveness Multiple processors Dangers Race Conditions Deadlock Child Thread C# Threading

Spawning a new Thread IO Delegates System.Thread C# Threading

Threading IO 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 C# Threading

Threading a Delegate (See DelegateThreading Demo) 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) C# Threading

IAsyncResult Members: AsyncResult object AsyncState AsynchWaitHandle 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# Threading

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() C# Threading

Thread Static Members CurrentThread Sleep(int ticks) 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 C# Threading

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 C# Threading

Thread Properties IsBackground Priority ThreadState 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 C# Threading

Thread Methods Start() Suspend() Resume() Interrupt() 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 C# Threading

Thread Methods (Continued) Abort() Attempts to abort the thread Throws a ThreadAbortException Join() Blocks the calling thread until the owning thread terminates C# Threading

Exceptions Between threads Must be handled in the thread it was thrown in Exceptions not handled in the thread are considered unhandled and will terminate that thread C# Threading

Threading Dangers volatile Fields Race Conditions Deadlock 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 other to release resources C# Threading

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; C# Threading

Race Conditions Covered thoroughly in CNS 3060 Solved using a Mutex or Monitor Called Synchronization C# Threading

Synchronization Classes and Constructs lock keyword Mutex class Monitor class Interlocked class ReaderWriterLock class C# Threading

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 } C# Threading

The lock Mutex lock defines one Mutex for each object locked on Blocks until the current thread is finished (See Lock Demo) C# Threading

Mutex Class Stands for Mutual-Exclusion Blocking synchronization object WaitOne() Begins the critical section ReleaseMutex() Ends critical section Call ReleaseMutex() in a finally block C# Threading

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 C# Threading

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 C# Threading

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 C# Threading

Deadlock Your job to avoid it object1 waiting for has Resource1 C# Threading

Windows Threading 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) C# Threading

Mediator Pattern Specialization GUI Thread Mediator Worker Thread subscribes Exposed Event fires when needed public FireEvent() C# Threading