I am very new to C# and I wanted to ask if I have this situation in MULTI THREADS (pseudo code):
public class ClassA
{
ClassB c = new ClassB();
public void someMethod()
{
c.myVar = 1;
// Some other stuff
c.myVar = 0;
}
}
public class ClassB
{
internal int myVar;
public void MethodA()
{
if(myVar = 1)
myVar = 0;
}
}
If someMethod()
and MethodA()
can be active in separate threads, then MethodA()
could evaluate the if statement as true; but before it sets myVar = 0
, someMethod()
sets myVar = 0
making it incorrect to have set myVar
to 0 in MethodA()
!!
Basically, how do I lock myVar
:
lock{}
on myVar
's property (set, get) Interlock
(I have no experience yet of Interlock
though)?Only one thread can hold a lock at a time. If a thread tries to take a lock that is already held by another thread, then it must wait until the lock is released.
If a thread tries to acquire a lock currently owned by another thread, it blocks until the other thread releases the lock. At that point, it will contend with any other threads that are trying to acquire the lock. At most one thread can own the lock at a time.
When race conditions occur. A race condition occurs when two threads access a shared variable at the same time. The first thread reads the variable, and the second thread reads the same value from the variable.
A lock may be a tool for controlling access to a shared resource by multiple threads. Commonly, a lock provides exclusive access to a shared resource: just one thread at a time can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first.
You should create a private object that will allow for locking:
private readonly object _locker = new object();
Then in your property get/set methods, lock around it:
get { lock (_locker) { return this.myVar; } }
set { lock (_locker) { this.myVar = value; } }
Make sure your method uses the lock also:
public void MethodA()
{
lock(_locker)
{
if(myVar == 1)
myVar = 0;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With