juin

16

Posted by : admin | On : 16 juin 2014

sample code

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Concurrent;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Action<Action> mesure = (body) =>
                {
                    var startTime = DateTime.Now;
                    body();
                    Console.WriteLine("{0} {1}", DateTime.Now - startTime, Thread.CurrentThread.ManagedThreadId);
                };

            Action calJob = () => { for (int i = 0; i < 350000000; i++); };
            Action ioJob = () => { Thread.Sleep(1000); };

            // TPL on top of thread
            /* mesure(() =>
                 {
                  var tasks = Enumerable.Range(1,10)
                              .Select(_ => Task.Factory.StartNew(() => mesure(ioJob)))
                              .ToArray();
                  Task.WaitAll(tasks); // Start 2 task in background
                 });*/

            //Parallel.For(1, 10, _ => { mesure(ioJob); });

            //PLINQ on top TPL
            //use of multiple core

            //Enumerable.Range(1,10).ToList().ForEach(_=>mesure(ioJob)); //no sort order
            //Enumerable.Range(1, 10).AsParallel().WithDegreeOfParallelism(10).ForAll(_ => mesure(ioJob));
            //ThreadPool.SetMinThreads(5, 5);
            // ParallelEnumerable.Range(1, 10).WithDegreeOfParallelism(10).ForAll(_ => mesure(calJob)); 

            //producer Xml reader => queue => consumer
            //var queue = new Queue<int>();

            var queue = new BlockingCollection<int>(100);// concurrent Queue
            var producers = Enumerable.Range(1, 10).Select(_ => Task.Factory.StartNew(() =>
            {
                Enumerable.Range(1, 100)
                    .ToList()
                    .ForEach(i =>
                {
                    queue.Add(i);
                    Thread.Sleep(100);
                });
            })).ToArray();

            var consumers = Enumerable.Range(1, 2).Select(_ => Task.Factory.StartNew(() =>
            {
                foreach(var item in queue.GetConsumingEnumerable()) //get next element and remove from the queue 
                {
                   Console.WriteLine(item);
                };
            })).ToArray();

            Task.WaitAll(producers); // run all producers 
            queue.CompleteAdding(); // when all producers have finished so that it will notify to the consumers when the queue is dequeue 

            Task.WaitAll(consumers);
            Console.ReadKey();
        }
    }
}