Home > Development > Tasks and Mutex for Locking

Tasks and Mutex for Locking


When you use Tasks you often need to protected data. The code that accesses the critical data is known as the critical region aka protected section. You can use mutexes or locks. Note mutexes are slower than locks and this is just to show the usage. Prefer locks unless you need cross process locks.

To obtain the lock call WaitOne() and Release it after with ReleaseMutex().

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

namespace TPLSamples
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Program p = new Program();
            p.TestingMutexes();

            Console.WriteLine("Press any key to quit...");
            Console.ReadKey();
        }

        public void TestingMutexes()
        {
            Mutex mutex = new Mutex();
            Random random = new Random();
            Action action = () =>
            {
                
                Thread.Sleep(random.Next(3000));
                mutex.WaitOne();
                Console.WriteLine("Task {0} has the lock", Task.CurrentId);
                mutex.ReleaseMutex();
            };

            Task t1 = new Task(action);
            Task t2 = new Task(action);
            Task t3 = new Task(action);

            t1.Start();
            t2.Start();
            t3.Start();

            Task.WaitAll(t1, t2, t3);

        }
    }
}

Blair..

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: