How to prevent method from running in multiple instances

Viewed 139

I created a method that polls a database. If two instances of the exe are run, I wouldn't want both instances to be able to run the polling method simultaneously.

How might I best ensure the polling method is only ever active in one thread (regardless of which process owns the thread), and that if another thread calls it it will throw an exception?

1 Answers

I would use Mutex to avoid multiple access to the same recourses.

Here you have a brief piece of code to achieve this

    Mutex mutex;
    private void StartPolling()
    {
        mutex = new Mutex(true, "same_name_in_here", out bool createdNew);
        if (!createdNew) { throw new Exception("Polling running in other process"); }
        //now StartPolling can not be called from other processes

        //polling stuff in here
    }

    private void StopPolling()
    {
        mutex?.Dispose();
        mutex = null;
        //now StartPolling can be called from other processes
        //Stop any polling operation
    }
Related