Home > Software engineering >  Fastest and relatively easy way to share data between two c# programs?
Fastest and relatively easy way to share data between two c# programs?

Time:10-21

I have a c# program that I want to run multiple copies simultaneously. They need to communicate to each other; basically they'll run to a point then check if any other program has reached this point yet and, if not, set a flag telling the other programs to wait until the first process completes. Then the other programs try to "take control"; the first one wins and the process repeats.

Note that I don't have a "master" program; they're all the same.

Using a back-end database I think would be too slow. I've considered using Memory Mapped files, but I'm concerned about two programs reading it and seeing that it's OK to proceed, but then they'll both try to write to the file simultaneously and something will break. I only need a flag that the programs can check and, if false, set to true in the same code block.

Ideally the solution will run fast and be not too complex.

Any suggestions would be greatly appreciated. Thanks.

CodePudding user response:

You can use a named mutex for this. These are very lightweight:

using System;
using System.Threading;

namespace Demo;

public static class Program
{
    static void Main()
    {
        using var handle = new Mutex(initiallyOwned:false, "EventNameHere");

        while (true)
        {
            Console.WriteLine("Obtaining lock.");
            handle.WaitOne();
            Console.WriteLine("Obtained lock. Simulating work");
            Thread.Sleep(4000);
            Console.WriteLine("Signalling lock.");
            handle.ReleaseMutex();
        }
    }
}

Try running several instances of that console application and you'll see that only one is simulating the work at once.

Note that this sample code is very simplistic - in the real world you will have to manage how the application shuts down and stops waiting for the mutex in order to avoid AbandonedMutexException

  • Related