首页 / .NET / 正文

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

25789 发布于: 2014-10-28 读完约需7分钟

.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;
    }
  }
}

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

上一篇: C#/.NET根据枚举Name获取对应的Value值

下一篇: .NET(C#)枚举的使用总结--获取键/值及键/值列表等

本文永久链接码友网 » .NET(C#)Parallel.ForEach()并行执行测试实例

分享扩散:

发表评论

登录用户才能发表评论, 请 登 录 或者 注册