intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Chapter 11 - Threading in C#

Chia sẻ: Thien Phuc | Ngày: | Loại File: PPT | Số trang:30

158
lượt xem
30
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

“This chapter covers the tasks required in creating multithreaded applications in the C# managed virtual execution environment. If you’re familiar with threading in the native Win32 environment, you’ll notice the significant differences. Moreover, the managed environment provides much more infrastructure for making the job easier. This chapter covers the various synchronization facilities available to your applications.”

Chủ đề:
Lưu

Nội dung Text: Chapter 11 - Threading in C#

  1. Chapter 11. Threading in C# Hoang Anh Viet VietHA@it-hut.edu.vn HaNoi University of Technology 1
  2. Objectives “This chapter covers the tasks required in creating multithreaded applications in the C# managed virtual execution environment. If you’re familiar with threading in the native Win32 environment, you’ll notice the significant differences. Moreover, the managed environment provides much more infrastructure for making the job easier. This chapter covers the various synchronization facilities available to your applications.” Microsoft Microsoft 2
  3. Roadmap 11.1 Threading in C# and .NET 11.2 Synchronizing Work Between Threads 11.3 Using ThreadPool Microsoft Microsoft 3
  4. 11.1 Threading in C# and .NET By default, a C# program has one thread. This thread  executes the code in the program starting and ending with the Main method. This thread terminates when Main returns.  However, auxiliary threads can be created and used to  execute code in parallel with the primary thread. These threads are often called worker threads. Microsoft Microsoft 4
  5. 11.1 Threading in C# and .NET Worker threads can be used to perform the following  without tying up the primary thread. • Time-consuming tasks. • Or time critical tasks. For example, worker threads are often used  • In server applications to fulfill incoming requests without waiting for the previous request to be completed. • To perform "background" tasks in desktop applications so that the main thread--which drives user interface elements--remains responsive to user actions. Microsoft Microsoft 5
  6. Multithreading Multithreading can introduce resource-sharing issues  • Deadlocks • And race conditions  Multiple threads are best for tasks that require different resources. • File handles • Network connections  Assigning multiple threads to a single resource causes • Synchronization issues • Threads frequently are blocked. Microsoft Microsoft 6
  7. States of a Thread Microsoft Microsoft
  8. Microsoft Microsoft
  9. Create and Terminate Threads The following example will demonstrate:  • How an auxiliary or worker thread can be created and used to perform processing in parallel with the primary thread. • Besides, making one thread wait for another and gracefully terminating a thread. Microsoft Microsoft
  10. Example using System; using System.Threading; } public class Worker { // This method will be called when the thread isIt started. will be public void DoWork() executed by { while (!_shouldStop) worker thread. { Console.WriteLine("worker thread: working..."); } } Console.WriteLine("worker thread: terminating requests It gracefully."); work thread to } } public void RequestStop() stop { _shouldStop = true; } // Volatile is used as hint to the compiler thatItthis data enables to // member will be accessed by multiple threads. safely access private volatile bool _shouldStop; } this member from multiple threads.
  11. Example { static void Main() } { // Create the thread object. This does not start the thread. Worker workerObject = new Worker(); Thread workerThread = new Declare Thread(workerObject.DoWork); and // Start the worker thread. workerThread.Start(); configure a Console.WriteLine("main thread: Starting worker thread..."); thread // Loop until worker thread activates. while (!workerThread.IsAlive); Thread.Sleep(1); // Request that the worker thread stop itself: workerObject.RequestStop(); Put the main // Use the Join method to block the current thread // until the object's thread terminates. thread to sleep workerThread.Join(); Console.WriteLine("main thread: Worker thread1has for millisecond terminated."); to allow the } worker thread to } do some work:
  12. 11.2 Synchronizing Work Between Threads Need synchronization primitives  • Way to ensure that only one thread executes code in a region at once • Called “critical section” C# provides (mostly in System.Threading)  • lock statement • Monitor class • Interrupt • several others (see Birrell’s paper or MSDN) Microsoft Microsoft 12
  13. Threading model: lock Basic idea: each object has a lock  public int Increment(ref int x) { lock(this) return ++x; } • lock prevents more than one thread from entering • forces sequential order What should we lock on?  • for instance variables: this • for globals and statics: typeof(container) • something that will be same for all threads that access this shared memory Microsoft Microsoft
  14. Threading model: Monitor Monitors provide synchronization construct  • entry waits on a queue • waiting lets a new thread enter Monitor.Enter and Monitor.Exit  • same semantics as the lock construct lock (x) { DoSomething(); } The same ? System.Object obj = (System.Object)x; System.Threading.Monitor.Enter(obj); try { DoSomething(); } finally { System.Threading.Monitor.Exit(obj); } Microsoft Microsoft
  15. Threading model: Monitor  Why do we need both? Gets a lock on the object  • Cannot be used on value types: why not?  Methods • Monitor.Enter/Monitor.Exit • enter/exit the monitor for a given object Microsoft Microsoft
  16. Threading model: Monitor Methods  • Monitor.Wait • wait on a given object • must be inside a monitor for that object • signal-delayed semantics • Monitor.Pulse/Monitor.PulseAll • some thread(s) can be released to try the monitor Microsoft Microsoft
  17. Threading model: Interrupt Sometimes need to wake up a thread  • eg. if UI cancelled • eg. if event no longer needed Standard OO way: exceptions  • Interrupt causes thread to throw ThreadInterruptedException • only on Wait or Sleep • Allows cleanup of invariants Microsoft Microsoft
  18. Semaphore What does it operate ?  • Allow a countable number of threads to acquire a resource simultaneously. • The semaphore count is decremented when a thread enters the semaphore via WaitOne or any of the other Wait...methods. • the count is incremented when an owning thread calls Release. • If a thread attempts to enter the semaphore when the count is zero, it will block until another thread calls Release Microsoft Microsoft
  19. Remark Create semaphore without a name ⇒ end up with a local  semaphore. • Usefully within the same process. • Need to synchronize access across multiple processes for security reasons. Microsoft Microsoft
  20. Other synchro classes Abort  • throws exception immediately • difficult to clean up: Why? • usually too draconian Mutex and other synchronization  • good for interacting with Windows • but stick with lock and Monitor, normally [ComVisibleAttribute(true)] [HostProtectionAttribute(SecurityActio. LinkDemand, Synchronization = true, ExternalThreading = true)] public sealed class Mutex : WaitHandle Microsoft Microsoft
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2