.NET(C#)Parallel.ForEach()并行执行测试实例

.NET 2014-10-28 19281阅读 0评论 0收藏 收藏本文
.NET的开发中(特别是WINFORM),经常会涉及到并行执行。.NET提供了Parallel.ForEach()的方法,可以完成并行执行任务。以下是对Parallel.ForEach()的测试样本:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ParallelForEachDemo
{
  public class Store
  {
    public int Id { get; set; }
    public string Domain { get; set; }
    public int SleepTime { get; set; }
  }
  public class Program
  {
    static void Main(string[] args)
    {
      var stores = new List<Store> { 
        new Store{Id=1,Domain="yahoo.com",SleepTime=6000},
        new Store{Id=2,Domain="google.com",SleepTime=5000},
        new Store{Id=3,Domain="baidu.com",SleepTime=4000},
        new Store{Id=4,Domain="sina.com.cn",SleepTime=3000},
        new Store{Id=5,Domain="163.com",SleepTime=2000},
        new Store{Id=6,Domain="21cn.com",SleepTime=10000}
      };
      Console.ReadKey();
      var ids = GetIds(stores);
      Console.WriteLine("Id list:{0}", string.Join(",", ids));
      Console.ReadKey();
    }

    private static CancellationTokenSource cts = new CancellationTokenSource();

    static List<int> GetIds(List<Store> stores)
    {
      var ids = new List<int>();
      var threadCounter = 0;
      var token = cts.Token;
      try
      {
        var pr = Parallel.ForEach(stores, new ParallelOptions { MaxDegreeOfParallelism = 10, CancellationToken = token }, store =>
        {
          threadCounter++;
          Console.WriteLine("Current threads:{0},Current thread id:{1}", threadCounter, Thread.CurrentThread.ManagedThreadId);
          //var rand = new Random();
          //var sleep = rand.Next(100, 10000);
          if (threadCounter > 3)
          {
            cts.Cancel(true);
          }
          Console.WriteLine("Store id:{0},sleep seconds:{1}", store.Id, store.SleepTime);
          Thread.Sleep(store.SleepTime);
          Console.WriteLine("Store id:{0} completed!!!", store.Id);
          ids.Add(store.Id);
        });
        Console.WriteLine("ALL STORES ARE COMPLETED?{0}", pr.IsCompleted);
      }
      catch (OperationCanceledException ex)
      {
        Console.WriteLine("Task was canceled!!!{0}", ex.Message);
      }
      //Console.WriteLine("All stores are completed!!!");
      return ids;
    }
  }
}
 

转载请注明:图享网 » .NET(C#)Parallel.ForEach()并行执行测试实例

文章评论

获取验证码