简体   繁体   中英

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.

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.

您可以使用lock来确保只有一个线程可以进入由lock语句封装的关键块。

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); } try {} finalley { Monitor.Exit(obj); } to release your lock obj again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM