Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

c# lock

8 views
Skip to first unread message

Nalaka

unread,
Jun 11, 2007, 8:31:59 PM6/11/07
to
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


Arne Vajhøj

unread,
Jun 11, 2007, 8:48:22 PM6/11/07
to

Try look at Monitor.TryEnter !

Arne

Nicholas Paldino [.NET/C# MVP]

unread,
Jun 11, 2007, 8:43:38 PM6/11/07
to
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]
- m...@spam.guard.caspershouse.com

"Nalaka" <nala...@nospam.nospam> wrote in message
news:%23mRnXkI...@TK2MSFTNGP03.phx.gbl...

Nalaka

unread,
Jun 12, 2007, 12:29:27 PM6/12/07
to
Hi,
I need to code so that only one thread can do a piece of work... other
threads need not do the work if a thread is alredy doing the work.

something like this.....

if ( isAlreadyLocked )
{ return anotherThreadIsAlredyAtWork }

lock ( myObject )
{
// do the work
}


Any help is appreciated
Thanks
Nalaka


Nicholas Paldino [.NET/C# MVP]

unread,
Jun 12, 2007, 12:44:53 PM6/12/07
to
What was wrong with the previous answers?

http://groups.google.com/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/3b12fd804074b36d/3928a655441147c5?lnk=st&q=Nicholas+Paldino+c%23+lock&rnum=2#3928a655441147c5


--
- Nicholas Paldino [.NET/C# MVP]
- m...@spam.guard.caspershouse.com

"Nalaka" <nala...@nospam.nospam> wrote in message

news:ucPrZ7Qr...@TK2MSFTNGP03.phx.gbl...

Nalaka

unread,
Jun 12, 2007, 12:49:29 PM6/12/07
to
aaah sorry Nicholas,
I am using outLook express to look at this thread... it does not show my
yesterday's post.
I thought my yestreday's post did not go through... thats why I posted
again.

sorry again
Nalaka

"Nicholas Paldino [.NET/C# MVP]" <m...@spam.guard.caspershouse.com> wrote in
message news:eFVNECR...@TK2MSFTNGP02.phx.gbl...

0 new messages