0

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


    }
  }

Edited by Reverend Jim: Fixed formatting

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by JerryShaw
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

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.