7 responses to “Disabling Events in ShowUI”

  1. Dew Drop – June 28, 2011 | Alvin Ashcraft's Morning Dew

    [...] Disabling Events in ShowUI (Joel Bennett) [...]

  2. ross

    Certainly not what I intuitively expected. I tried this in Visual Studio, and the WPF version behaved the same way as the Winforms. Haven’t tried from powershell.

    I wonder if your example doesn’t work that well because you are using sleep, which is putting the UI thread to sleep and not simulating background work.

    Here is a VS c# example that uses a timer to simulate a background thread, perhaps more realistic, and some code that might not be perfect but roughly addresses the problem I think.

    private int _cnt;
    private static object _syncLock = new object();
    private Timer _timer;

    private void button1_Click(object sender, EventArgs e)
    {
    if (button1.Enabled)
    {
    bool go = false;
    lock (_syncLock)
    {
    go = button1.Enabled;
    button1.Enabled = false;
    }
    if (go)
    {
    _cnt++;
    textBox1.Text += _cnt.ToString() + Environment.NewLine;

    _timer = new Timer() { Interval = 3000 };
    _timer.Tick += (s, args) =>
    {
    _timer.Stop();
    button1.Enabled = true;
    };

    _timer.Start();

    }
    }

  3. ross

    I am not an expert in how the Windows message loop works, and how it relates to the implementation of WPF / Winforms. But because WPF/Winforms are single threaded, the behaviour you are seeing is what I would expect.

    Let’s assume there are 3 clicks on the button, I see the callstack / flow of execution as follows :

    1. 1st Click
    a) Click handler
    b) Set button disabled
    c) Do some work / sleep
    d) Set button enabled
    2. 2nd Click
    a) Button is now enabled again from 1d, so Click handled
    b) Set button disabled
    c) Do some work / sleep
    d) Set button enabled
    2. 3rd Click
    a) Button is now enabled again from 2d, so Click handled
    b) Set button disabled
    c) Do some work / sleep
    d) Set button enabled