Search code examples
c#winformstimerpropertygridshowdialog

ShowDialog, PropertyGrid and Timer problem


I have a strange bug, please, let me know if you have any clues about the reason.

I have a Timer (System.Windows.Forms.Timer) on my main form, which fires some updates, which also eventually update the main form UI. Then I have an editor, which is opened from the main form using the ShowDialog() method. On this editor I have a PropertyGrid (System.Windows.Forms.PropertyGrid).

I am unable to reproduce it everytime, but pretty often, when I use dropdowns on that property grid in editor it gets stuck, that is OK/Cancel buttons don't close the form, property grid becomes not usable, Close button in the form header doesn't work.

There are no exceptions in the background, and if I break the process I see that the app is doing some calculations related to the updates I mentioned in the beginning.

What can you recommend? Any ideas are welcome.


Solution

  • What's happening is that the thread timer's Tick method doesn't execute on a different thread, so it's locking everything else until it's done. I made a test winforms app that had a timer and 2 buttons on it whose events did this:

    private void timer1_Tick(object sender, EventArgs e)
    {
        Thread.Sleep(6000);
    }
    
    private void button1_Click(object sender, EventArgs e)
    {
        timer1.Start();
    }
    
    private void button2_Click(object sender, EventArgs e)
    {
        frmShow show = new frmShow();
        show.ShowDialog(); // frmShow just has some controls on it to fiddle with
    }
    

    and indeed it blocked as you described. The following solved it:

    private void timer1_Tick(object sender, EventArgs e)
    {
        ThreadPool.QueueUserWorkItem(DoStuff);
    }
    
    private void DoStuff(object something)
    {
        Thread.Sleep(6000);
    }