Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Chạy LINQ truy vấn trong song song 18,17: Hủy một vòng lặp song song bằng cách sử dụng sử dụng sử dụng sử dụng sử dụng hệ thống; System.Collections.Generic; | Running LINQ Queries in Parallel 737 Listing 18.17 Canceling a Parallel Loop using System using System.Collections.Generic using System.Linq using System.Threading using System.Threading.Tasks public class Program public static List string ParallelEncrypt List string data CancellationToken cancellationToken return data.AsParallel .WithCancellation cancellationToken .Select item Encrypt item .ToList public static void Main List string data Utility.GetData 1000000 .ToList CancellationTokenSource cts new CancellationTokenSource Console.WriteLine Push ENTER to exit. Task task Task.Factory.StartNew data ParallelEncrypt data cts.Token cts.Token Wait for the user s input Console.Read cts.Cancel Console.Write stars try task.Wait catch AggregateException . Output 18.8 ERROR The operation was canceled. Chapter 18 Multithreading As with a parallel loop canceling a PLINQ query requires a CancellationToken which is available on a CancellationTokenSource.Token property. However rather than overloading every PLINQ query to support the cancellation token the ParallelQuery T object returned by lEnumera-ble s AsParallel method includes a WithCancellation extension method that simply takes a CancellationToken. As a result calling Can-cel on the CancellationTokenSource object will request the parallel query to cancel because it checks the IsCancellationRequested property on the CancellationToken. As mentioned canceling a PLINQ query will throw an exception in place of returning the complete result. Therefore all canceled PLINQ queries will need to be wrapped by try . catch OperationCanceledExcep-tion . blocks to avoid an unhandled exception. Alternatively as shown in Listing 18.17 pass the CancellationToken to both ParallelEncrypt and as a second parameter on StartNew . This will cause task.Wait to throw an AggregateException whose InnerException property will be set to a TaskCanceledException. Multithreading before .NET Framework 4 TPL is a fantastic library covering a multitude of .