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


    }
  }

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.