Marcel Lambacher
Marcel Lambacher

Reputation: 47

Locking two methods and ensure that only on thread is calling one method

In a class I've two methods:

This class can be accessed by multiple threads. How can I realise, if "thread1" call "Method1", that "thread2" is waiting in "Method2" or in "Method1". This logic should also work, if "thread2" is calling "Method2", that "thread1" is waiting in "Method1" or "Method2"

My idea is this:

private object _lock = new object();

void Method1() {
 lock(_lock){
  //TODO: do something
 }
}

void Method2() {
 lock(_lock){
  //TODO: do something
 }
}

Will this work?

Upvotes: 2

Views: 2630

Answers (5)

Lasse V. Karlsen
Lasse V. Karlsen

Reputation: 391336

Your code will work after your clarification in comments.

With the given code you will:

  1. Ensure only one thread can execute either Method1 or Method2 at the same time
    1. If one thread is inside Method1, other threads will wait if they try to call either Method1 or Method2.
  2. If Method1 calls into Method2 or vice versa, this will also work as the same thread can lock the same object more than once.

    In other words, this is not a deadlock:

    lock (x)
        lock (x)
            ....
    

So your code should work just fine.

Upvotes: 1

imlokesh
imlokesh

Reputation: 2719

This will work. Since you're locking on the same object, only one lock { } block will be executed at a given time.

How can I realise, if "thread1" call "Method1", that "thread2" is waiting in "Method2" or in "Method1". This logic should also work, if "thread2" is calling "Method2", that "thread1" is waiting in "Method1" or "Method2"

The logic will work. But not sure what you're trying to ask here.

Upvotes: 0

AhmadWabbi
AhmadWabbi

Reputation: 2197

Your methods should be Synchronized. See C# version of java's synchronized keyword? to get an idea on how to do it in c#.

Upvotes: 0

Mark Rawson
Mark Rawson

Reputation: 126

You can use the WaitOne() function of an AutoResetEvent to allow only one function to access resources at a time, when it's finished called Set().

Example here: Synchronizing two threads with AutoResetEvent

MSDN Reference: https://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(v=vs.110).aspx

Upvotes: 0

Vivek Nuna
Vivek Nuna

Reputation: 1

You cant do on same object, You can use Monitor. Monitor allows re-entrancy

Upvotes: 0

Related Questions