user4805530
user4805530

Reputation:

Calling methods from different threads

I have 4 windows forms and they use one method of one another form. This method must be processed just by one of the forms. If a thread wants to use this method, it must be sure that method is not called at this time by other threads.

I have a solution like that

bool methodIsBusy = false;

void Method()
{
     methodIsBusy = true;

     //do method things

     //done method things

     methodIsBusy = false;

}

and use methodIsBusy to know that method is occupied by a thread or not. Are any more creative solutions to this problem? Thanks.

Upvotes: 2

Views: 120

Answers (3)

Patrick Artner
Patrick Artner

Reputation: 51683

Also have a look at Monitor.TryEnter - which allows you to test if you can enter, not lock and go out w/o doing somth. Just make really sure to use a try {} finalley { Monitor.Exit(obj); } to release your lock obj again.

Upvotes: -1

John Wu
John Wu

Reputation: 52290

The simplest traditional pattern would be more like this, using lock. Code inside of a lock (referred to as a critical section) can only be executed by one thread at a time.

object lockObject = new object();  //Can be anything, an object will do

void Method()
{
     lock (lockObject)
     {

         //do method things

         //done method things

     }    
}

You could in theory use a bool but you'd have to write busywait code, like this:

//Don't do this!
while (methodIsBusy)
{
    System.Threading.Thread.Sleep(10); //or some number
}

This kind of code will end up using more resources than a lock, which is designed for exactly this purpose.

Upvotes: 4

Progman
Progman

Reputation: 19555

You can use a lock to ensure that only one thread can enter a critical block capsuled with a lock statement.

Upvotes: 0

Related Questions