-13

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?

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
BVernon
  • 3,205
  • 5
  • 28
  • 64
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/247979/discussion-on-question-by-bvernon-how-to-prevent-method-from-running-in-multiple). – Samuel Liew Sep 12 '22 at 06:36

1 Answers1

3

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
    }
Hytac
  • 147
  • 1
  • 7