tailieunhanh - Microsoft Visual C# 2010 Step by Step (P15)
Tham khảo sách 'microsoft visual c# 2010 step by step (p15)', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | 670 Part VI Building Professional Solutions with Visual Studio 2010 The following code shows how to use a BlockingCollection T object to wrap an instance of a user-defined type called MyCollection T that implements the IProducerConsumerCollection interface. It limits the number of items in the underlying collection to 1000. class MyCollection T IProducerConsumerCollection T Implementation details not shown Create an instance of MyCollection T and wrap it in a BlockingCollection T object MyCollection int intCollection new MyCollection int BlockingCollection int collection new BlockingCollection int myCollection 1000 Note You can also instantiate a BlockingCollection T object without specifying a collection class. In this case the BlockingCollection T object creates a ConcurrentQueue T object internally. Adding thread-safety to the methods in a collection class imposes additional runtime overhead so these classes are not as fast as the regular collection classes. You need to bear this fact in mind when deciding whether to parallelize a set of operations that require access to a shared collection. Using a Concurrent Collection and a Lock to Implement Thread-Safe Data Access In the following set of exercises you will implement an application that calculates PI by using a geometric approximation. Initially you will perform the calculation in a single-threaded manner then you will change the code to perform the calculation by using parallel tasks. In the process you will uncover some data synchronization issues you need to address and that you will solve by using a concurrent collection class and a lock to ensure that the tasks coordinate their activities correctly. The algorithm you will implement calculates PI based on some simple mathematics and statistical sampling. If you draw a circle of radius r and draw a square with sides that touch the circle the sides of the square are 2 r in length as shown in the following image Chapter 28 Performing Parallel Data Access 671
đang nạp các trang xem trước