Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 30 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
30
Dung lượng
476 KB
Nội dung
Chapter 11. Threading in C# Hoang Anh Viet VietHA@it-hut.edu.vn HaNoi University of Technology 1 MicrosoftMicrosoft Objectives 2 “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.” MicrosoftMicrosoft Roadmap 11.1 Threading in C# and .NET 11.2 Synchronizing Work Between Threads 11.3 Using ThreadPool 3 MicrosoftMicrosoft 11.1 Threading in C# and .NET 4 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. MicrosoftMicrosoft 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. 5 MicrosoftMicrosoft Multithreading 6 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. MicrosoftMicrosoft States of a Thread MicrosoftMicrosoft MicrosoftMicrosoft 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. using System; using System.Threading; public class Worker { // This method will be called when the thread is started. public void DoWork() { while (!_shouldStop) { Console.WriteLine("worker thread: working "); } Console.WriteLine("worker thread: terminating gracefully."); } public void RequestStop() { _shouldStop = true; } // Volatile is used as hint to the compiler that this data // member will be accessed by multiple threads. private volatile bool _shouldStop; } Example } } It will be executed by worker thread. It requests work thread to stop } It enables to safely access this member from multiple threads. [...]... “critical section” • C# provides (mostly in System .Threading) • lock statement • Monitor class • Interrupt • several others (see Birrell’s paper or MSDN) Microsoft 12 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:... 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 Example •Create a new Mutex •The creating using System; using System .Threading; thread does class Tester not own the... parallel work • eg N-Body problem • automatically scales to number of processors • “embarrasingly parallel” problems Microsoft Example using System; using System .Threading; public class Fibonacci { public Fibonacci(int n, ManualResetEvent doneEvent) { _n = n; _doneEvent = doneEvent; } public void ThreadPoolCallback(Object threadContext) { int threadIndex = (int)threadContext; Console.WriteLine("thread {0}... Console.WriteLine("thread {0} started ", threadIndex); _fibOfN = Calculate(_n); Console.WriteLine("thread {0} result calculated ", threadIndex); _doneEvent.Set(); } public int Calculate(int n) { if (n . .NET 11. 2 Synchronizing Work Between Threads 11. 3 Using ThreadPool 3 MicrosoftMicrosoft 11. 1 Threading in C# and .NET 4 By default, a C# program has one thread. This thread executes the code in. Chapter 11. Threading in C# Hoang Anh Viet VietHA@it-hut.edu.vn HaNoi University of Technology 1 MicrosoftMicrosoft Objectives 2 “This chapter covers the tasks required in creating multithreaded. that the main thread which drives user interface elements remains responsive to user actions. 5 MicrosoftMicrosoft Multithreading 6 Multithreading can introduce resource-sharing issues • Deadlocks • And