The Parallel class is part of framework 4.0

The Parallel class gives us the ability to process data over multiple cores wich are available. Therefore there are the following methods available:

 

For

The parallel for methods splits your for into pieces and divides it processing over the available cores in the processor:

    public class Work
    {
        private int aantal;
        public void Do()
        {
            System.Threading.Tasks.Parallel.For(1, 1000000000, a => DoWork());
            System.Windows.Forms.MessageBox.Show(aantal.ToString());
        }

        private void DoWork()
        {
            aantal += 1;
        }
    }

ForEach

The parallel foreach processes your collection splitted over the different cores.

    public class Work
    {
        private List foundfiles =new List();
        public void Do()
        {
            Parallel.ForEach(new DirectoryInfo(@"c:\").GetFiles(), a => DoWork(a.FullName));
            
        }

        private void DoWork(string filename)
        {
            foundfiles.Add(filename);
        }
    }

Invoke

The parallel invoke processs your actions in parallel over the different cores ( if possible and if it will not degree the performance otherwise it will run sequentially), it also catches the different exceptions and bundles it in a aggregate exception ( like the Task library ). ConcurrentBag is a thread save unordered list of objects.

    public class Work
    {
        private ConcurrentBag counters = new ConcurrentBag();

        public void Do()
        {
            try
            {

                Parallel.Invoke(
                    CountTo100,
                    CountTo200,
                    CountTo900
                        );
            }
            catch (AggregateException aggregateexception)
            {
                foreach (Exception exception in aggregateexception.InnerExceptions)
                {
                    throw exception;  
                }
            }    
        }

        private void CountTo100()
        {
            for (int i = 0; i < 100; i++)
            {
                counters.Add(i);
            }
        }

        private void CountTo200()
        {
            for (int i = 0; i < 200; i++)
            {
                counters.Add(i);
            }
        }

        private void CountTo900()
        {
            for (int i = 0; i < 900; i++)
            {
                counters.Add(i);
            }
        }
    }

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!