|
C# 4.0支持并行任务,并行任务能提高CPU的利用率(尤其是当前CPU基本都是多核情况下),缩短处理时间- using System;
- using System.Threading;
- using System.Diagnostics;
-
- namespace ParrallelTask
- {
- class Program
- {
- static void Main(string[] args)
- {
- Stopwatch stopWatch = new Stopwatch();
- stopWatch.Start();
- DoSomeWork();
- DoSomework2();
- stopWatch.Stop();
- Console.WriteLine("Time consumed: {0}", stopWatch.Elapsed);
- }
-
- public static void DoSomeWork()
- {
- Thread.Sleep(1000);
- Console.WriteLine("Work completed");
- }
- public static void DoSomework2()
- {
- Thread.Sleep(1000);
- Console.WriteLine("Work completed2");
- }
-
- }
- }
复制代码- using System;
- using System.Threading;
- using System.Diagnostics;
- using System.Threading.Tasks;
-
-
- namespace ParrallelTask
- {
- class Program
- {
- static void Main(string[] args)
- {
- Stopwatch stopWatch = new Stopwatch();
- stopWatch.Start();
- Parallel.Invoke(
- new Action(DoSomeWork),
- new Action(DoSomework2)
- );
- stopWatch.Stop();
- Console.WriteLine("Time consumed: {0}", stopWatch.Elapsed);
- }
-
- public static void DoSomeWork()
- {
- Thread.Sleep(1000);
- Console.WriteLine("Work completed");
- }
- public static void DoSomework2()
- {
- Thread.Sleep(1000);
- Console.WriteLine("Work completed2");
- }
-
- }
- }
复制代码- List<int> nums = new List<int> { 1, 2, 3, 4 };
- Parallel.ForEach(nums, (item) =>
- {
- Console.WriteLine("针对集合元素{0}的一些工作代码……", item);
- });
复制代码- static void Main(string[] args)
- {
- Parallel.Invoke(
- () =>
- {
- Console.WriteLine("任务1……");
- },
- () =>
- {
- Console.WriteLine("任务2……");
- });
- Console.ReadKey();
- }
复制代码 |
|