Monitor.TryEnter waittime?

  • Thread starter Thread starter Rainer Queck
  • Start date Start date
R

Rainer Queck

Hello NG,

is there a possibillity to determine how long a thread had to wait on
Monitor.TryEnter(lockObj,timeout) ?

Thanks for hints.
Rainer Queck
 
is there a possibillity to determine how long a thread had to wait on
Monitor.TryEnter(lockObj,timeout) ?

Only by timing it - e.g. using the Stopwatch class.

Jon
 
Rainer said:
Hello NG,

is there a possibillity to determine how long a thread had to wait on
Monitor.TryEnter(lockObj,timeout) ?

You could take a snapshot of DateTime.Now both before and after it
acquires the lock, subtract them and interrogate the resulting TimeSpan:

DateTime startAcquire = DateTime.Now;
Monitor.TryEnter(lockObj,timeout);
DateTime endAcquire = DateTime.Now;

TimeSpan waitTime = endAcquire - startAcquire;


Chris.
 
Hi Jon, Hi Chris,

but would it be impossible to determine who does the StopWatch.Reset/Start
(or DateTime.Now) and who reads it?

Excample

StopWatch.Reset();
StopWatch.Start();
if(Monitor.TryEnter(lockObj,timeout) )
{
long ticks = StopWatch.ElapsedTicks();
DoTimeConsumingAccessToResource();
}

lets assume
thread1 comes. No Problem
while thread 1 is still working inside thread two come and has to wait.
Still no problem
BUT now it thread3 comes allong thread 1 is STILL working, it will do a
reset of the StopWatch before it starts waiting, won't it?
Now if thread2 can enter, ticks will have a wrong value true?

Regards
Rainer
 
but would it be impossible to determine who does the StopWatch.Reset/Start
(or DateTime.Now) and who reads it?

You'd create a separate Stopwatch for that particular call - only that
thread would even know about it.

Jon
 
Thanks for that hint.
I wasn't sure that local vars are "on the stack".

Regards
Rainer
 

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