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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
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
Well, slightly better than in pure C#, however, still worse than JNI. It’s time to go down.