This is the fourth part of the Concurrency series. For your convenience you can find other parts in the table of contents in Part 1 – Mutex performance in .NET

We have already seen a mutex in C# but last time it happened that Java JNI is faster. Let’s compare it with P/Invoke.

Code

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace MutexPInvoke
{
    class Program
    {
        [DllImport("kernel32.dll")]
        static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool bInitialOwner, string lpName);

        [DllImport("kernel32.dll", SetLastError = true)]
        static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);

        [DllImport("kernel32.dll")]
        public static extern bool ReleaseMutex(IntPtr hMutex);

        static void Main(string[] args)
        {
            IntPtr mutex = CreateMutex(IntPtr.Zero, false, "mutex_pinvoke");

            Stopwatch watch = new Stopwatch();

            while (true)
            {
                watch.Restart();
                for (int i = 0; i < 100000; ++i)
                {
                    WaitForSingleObject(mutex, 0xFFFFFFFF);
                    ReleaseMutex(mutex);
                }
                watch.Stop();
                Console.WriteLine(watch.ElapsedMilliseconds);
            }
        }
    }
}

As always, nothing special. Let's see the results.

Results

    \[ \begin{array}{cc} Number\ of\ processes & Time [ms] \\ 1 & 110\\ 2 & 620\\ 3 & 1011\\ 4 & 1346\\ 5 & 1728\\ 6 & 2072\\ 7 & 2456\\ 8 & 2803\\ 9 & 3254\\ 10 & 3627\\ \end{array} \]

Well, slightly better than in pure C#, however, still worse than JNI. It's time to go down.