P/Invoke Tutorial: Pinning (Part 4)

Sometimes a C/C++ function needs to store data you pass to it for later reference. If such data is a managed object (like a string or class) you need to make sure that the garbage collector doesn’t delete it while it’s still used/stored in the native code.

That’s what pinning is for. It prevents the garbage collector from deleting and moving the object.

Read more →

Breaking .NET’s Random class

Security is hard. In a current project I saw some code that created some access tokens based on a random number generator – .NET’s Random class. The code used an instance of Random stored in static field and I got curious:

If you have such a long living Random instance, could you predict the random values after generating a few of them?

It turns out, it is possible. And you only need to read 56 55 “random” values to predict all future values.

Read more →

Mutexes in .NET

The Mutex class in .NET is a little bit tricky to use.

Here’s an example how I got it to do what I want:

/// <summary>
/// A simple, cross application mutex. Use <see cref="Acquire"/> to acquire it
/// and release it via <see cref="Dispose"/> when you're finished.
/// </summary>
/// <remarks>
/// Only one thread (and thus process) can have the mutex acquired at the same
/// time.
/// </remarks>
public class SimpleMutex : IDisposable
    private readonly Mutex m_mutex;

    /// <summary>
    /// Acquires the mutex with the specified name.
    /// </summary>
    /// <param name="mutexName">the mutex's name</param>
    /// <param name="timeout">how long to try to acquire the mutex</param>
    /// <returns>Returns the mutex or <c>null</c>, if the mutex couldn't be
    /// acquire in time (i.e. the current mutex holder didn't release it in
    /// time).</returns>
    public static SimpleMutex Acquire(string mutexName, TimeSpan timeout)
        var mutex = new SimpleMutex(mutexName);
            if (!mutex.m_mutex.WaitOne(timeout))
                // We could not acquire the mutex in time.
                return null;
        catch (AbandonedMutexException ex)
            // We now own this mutex. The previous owner didn't
            // release it properly, though.

        return mutex;

    private SimpleMutex(string mutexName)
        this.m_mutex = new Mutex(false, mutexName);

    public void Dispose()

You can use it like this:

using (SimpleMutex.Acquire("MyTestMutex", Timeout.InfiniteTimeSpan))
    Console.WriteLine("Acquired mutext");

Console.WriteLine("Released mutext");

If you run your program twice, one will acquire the mutex and the other one will wait – until you press a key in the first one.

Note: If you forget to call Dispose() on this mutex, the operating system will make sure that the mutex is released when the program terminates. However, the next process trying to acquire this mutex will then get an AbandonedMutexException (which is handled properly in Acquire() though).

P/Invoke Tutorial: Passing strings (Part 2)

In the previous tutorial we passed a single string to a native C/C++ function by using P/Invoke.

This function was defined like this:

// C++
void print_line(const char* str);
// C#
private static extern void print_line(string str);

However, there exists a hidden pitfall here:

What happens when the user passes a non-ASCII character to this function?

Read more →