Home Splitting a collection over multiple threads
Post
Cancel

Splitting a collection over multiple threads

Inspired by http://www.drdobbs.com/windows/custom-parallel-partitioning-with-net-4/224600406?pgno=4

.net 4 source code

1
2
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
 [TestMethod]
 public void TestMethod2()
 {
    var list = new List<CustomerNotificationReply>();
    for (var i = 0; i < 1000; i++)
    {
        list.Add(new CustomerNotificationReply()
        {
            DateTime = DateTime.Now,
            NotificationId = 895,
            ReplyType = new Random((int)DateTime.Now.Ticks).Next(1, 12)
        });
    }

    var partitions = Partitioner.Create(list.ToArray()).GetPartitions(Environment.ProcessorCount);
    var tasks = (from partition in partitions
                select Task.Factory.StartNew(() =>
                {
                    using (partition)
                        body(partition);
                })).ToArray();
    Task.WaitAll(tasks);
}

private void body(IEnumerator<CustomerNotificationReply> partition)
{
    INotificationReplyDAL dal = new NotificationReplyDAL();
    while (partition.MoveNext())
    {
        var x = partition.Current;
        dal.InsertCustomerNotificationReply(x);
    }
}
This post is licensed under CC BY 4.0 by the author.