954,157 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

TryEnter always return true in Timer Event

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);
}
}


}
}

geossl
Newbie Poster
3 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

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

JerryShaw
Posting Pro in Training
465 posts since Nov 2006
Reputation Points: 69
Solved Threads: 75
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You