JSchwartz
JSchwartz

Reputation: 2724

Many threads to call same function, only one should make it

I have a function (Shutdown()) which is used to terminate my windows form (does some clean up and call this.close() at the end).

In my application I have threads of execution

Each one of these can call Shutdown(), either by the user pressing a button (UI), the timer expiring (timer), or the background worker completing his task. This leads me to a worry that if the timing is really bad I can have more then one thread calling Shutdown() at the same time.

So how can I ensure that only the first one that calls it will execute it? Any subsequent calls should just be ignored as the call will end in terminating the application anyways.

Upvotes: 0

Views: 125

Answers (1)

Peter Duniho
Peter Duniho

Reputation: 70671

It's not really clear from your question what the difficulty is. What have you tried? What trouble did you run into?

The obvious, trivial implementation would be something like this:

private readonly object _lock = new object();
private bool _shuttingDown;

public void Shutdown()
{
    lock (_lock)
    {
        if (_shuttingDown) return;

        _shuttingDown = true;
    }

    // do work here...
}

Is there some reason that doesn't work in your scenario? If so, please provide a good, minimal, complete code example that shows clearly what you've tried, a describe precisely what that code does and how that's different from what you want it to do.

Upvotes: 1

Related Questions