2

In a class I've two methods:

  • Method1(): void
  • Method2(): void

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?

5 Answers5

1

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.

Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
0

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

Vivek Nuna
  • 25,472
  • 25
  • 109
  • 197
0

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

Community
  • 1
  • 1
Mark Rawson
  • 116
  • 4
0

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

Community
  • 1
  • 1
AhmadWabbi
  • 2,253
  • 1
  • 20
  • 35
0

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.

imlokesh
  • 2,506
  • 2
  • 22
  • 26