943,692 Members | Top Members by Rank

Ad:
  • C# Discussion Thread
  • Unsolved
  • Views: 749
  • C# RSS
May 13th, 2009
0

TryEnter always return true in Timer Event

Expand Post »
Dear All,

That's strange that when I use TryEnter in Timer event which triggers every 1 sec, the TryEnter() always returns true. Why there is such an error?


public partial class Form1 : Form
{

private object BlockingObj = new object();

private void timer1_Tick(object sender, EventArgs e)
{

bool ret = System.Threading.Monitor.TryEnter(BlockingObj, 1);

if (ret){
try
{
DialogResult result = MessageBox.Show("test", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
}
finally
{
System.Threading.Monitor.Exit(BlockingObj);
}
}


}
}
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
geossl is offline Offline
3 posts
since May 2009
May 13th, 2009
0

Re: TryEnter always return true in Timer Event

Why do you think this is an error.
Your timer is on a 1000 ms loop, and the TryEnter has a max wait time of 1ms. It should always return true, because there was nothing preventing it (IOW nothing else locking the object for more than 1001ms.

Try having another method or timer that holds the lock for more than one second while the 1second timer is active, and see if it reacts the way you think it should.

// Jerry
Reputation Points: 69
Solved Threads: 75
Posting Pro in Training
JerryShaw is offline Offline
465 posts
since Nov 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C# Forum Timeline: changing colors of button
Next Thread in C# Forum Timeline: How to change settings of SQL Logins using Visual C# code?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC