I'm trying to find a way to provide exclusive access to a resource, while at the same time providing information about the state of the lock (_isWorking) for other classes to read.
Here's what I have come up with so far :
private int _isWorking = 0;
public bool IsWorking
{
get { return Interlocked.CompareExchange(ref _isWorking, 0, 0) == 1; }
}
public void LaunchProcess()
{
if (Interlocked.CompareExchange(ref _isWorking, 1, 0) == 0)
{
try
{
DoExpansiveProcess();
}
finally
{
Interlocked.Exchange(ref _isWorking, 0);
}
}
}
public void DoExpansiveProcess()
{
Thread.Sleep(30000);
}
It does not work exactly as a lock since the second thread, upon seeing that a thread is already running the process, will just leave the method and do nothing.
Is it the correct way to do this or are there any C# 3.5 structure more adapted for the purpose?
And how to implement a 'real' lock scenario, where the second thread would still execute the method after the first one finishes, while providing information about the state?