Reputation: 47
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
Reputation: 391336
Your code will work after your clarification in comments.
With the given code you will:
Method1
or Method2
at the same time
Method1
, other threads will wait if they try to call either Method1
or Method2
.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
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
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
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
Reputation: 1
You cant do on same object, You can use Monitor. Monitor allows re-entrancy
Upvotes: 0