c# lock

  • Thread starter Thread starter Nalaka
  • Start date Start date
N

Nalaka

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
 
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);
}
}
 
Nalaka said:
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

Try look at Monitor.TryEnter !

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top