长沙快付新闻资讯
您当前的位置是: 首页->技术资讯->.net网站技术问题

.net(C#)Parallel.ForEach()的测试样本

首发: 长沙快付 版权所有,未经许可严禁转载
   .NET的开发中(特别是WINFORM),经常会涉及到并行执行。.NET提供了Parallel.ForEach()的方法,可以完成并行执行任务。长沙做网站整理了Parallel.ForEach()的测试样本:

3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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;
    }
  }
}
  • 最新签约客户
  • 最新上线网站
为什么选择长沙快付公司?

8年专业做网站经验
帮助您解决各种需求,并得到满意方案

效果满意后付款
预付30%定金,效果让您满意后,付全款

资深用户体验设计师
秉承"一切以用户价值为依归"理念,重视用户体验,专为企业需求进行定制

采用国际标准结构建站
DIV+CSS国际标准构建网页,可有效提高网站访问速度、提高网站页面的可维护

实现网络营销[SEO]最大化
网站程序中融入SEO,有效降低企业成本

分享到: