How to work with parallelism without worrying about parallelism

I know. Work with threads and semaphores can be a nightmare sometimes.
However, fortunately, there’s a way to do some tasks without worry about how to do it in async manner!

Really? How can this be possible?

Do you know a class named Parallel?

If you write “Parallel” into your code, you’ll see this:

parallel

And yes, this is just a foreach loop, just like you do with lambda expressions!

So, imagine that scenario: You have 20 heavy tasks do to. Let’s suppose you need to upload 20 files to a file server by a c# console application.

To emulate this, let’s create a list with 20 items:

var list = new List<int>();

for (int i = 0; i < 20; i++)
     list.Add(i);

And a service class that “adds” these “files”:

public class ServiceLayer 
{
     public int ProcessItem(int item)
     {
         Thread.Sleep(1000);
         return item;
     }
}

So, the only thing here you have to do is to instantiate the service and use Parallel.Foreach instead foreach keyword or list.ForEach:

var service = new ServiceLayer();
Parallel.ForEach(list, item =>
{
    Console.WriteLine(service.ProcessItem(item));
});

If you run this code, will see something like this:
output

This unordered list proves that the loop was executed in parallel.

Here’s the entire code:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<int>();

            for (int i = 0; i < 20; i++)
                list.Add(i);

            var service = new ServiceLayer();
            Parallel.ForEach(list, item =>
            {
                Console.WriteLine(service.ProcessItem(item));
            });

            Console.ReadKey();
        }
    }

    public class ServiceLayer
    {
        public int ProcessItem(int item)
        {
            Thread.Sleep(1000);
            return item;
        }
    }
}

I hope you liked it!

See you! =)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s