Nalaka,
Instead of using lock, you will want to call the TryEnter method.
Because you will acquire the lock manually, you have to be sure to release
it as well. You will want something like this:
// Was the lock acquired?
bool lockAcquired = false;
// Enter try/finally.
try
{
// Try to acquire the lock.
if (!(lockAcquired = Monitor.TryEnter(myObject)))
{
// Get out.
return;
}
// Do your work here.
}
finally
{
// If the lock was acquired, then exit.
if (lockAcquired)
{
// Release the lock.
Monitor.Exit(myObject);
}
}
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
"Nalaka" <na******@nospam.nospamwrote in message
news:%2****************@TK2MSFTNGP03.phx.gbl...
Hi,
in C#... I have a method that need to be executed by only one thread at a
time.
And I want the the following threads to return without entering the
blocked code section.
( if some other thread is already doing the work, I do not have to do the
work)
Something like this....
if ( myObject is locked)
{
return alreadyRunning;
}
lock(myObject)
{
\\ do work
}
return didWork;
Any direction is deeply appreciated
Thanks
Nalaka