1

What happens when more than one thread tries to call a form method using Invoke which updates form controls at the same time in Winforms?

        static thCount = 0;
        private void button1_Click(object sender, EventArgs e)
        {
            System.Threading.Thread t1 = new System.Threading.Thread(start);           
            System.Threading.Thread t2 = new System.Threading.Thread(start);
            t1.Start();
            t2.Start();
        }    
        private void start()
        {
            System.Threading.Thread.Sleep(300);
            Invoke(new MethodInvoker(guiUpdate));
        }    
        private void guiUpdate()
        {
            this.label1.Text = "Updated.." + (thCount++);
            this.label1.Update();            
        }    
        private void Form1_Load(object sender, EventArgs e)
        {
            this.label1.Text = System.Threading.Thread.CurrentThread.Name;
        }
user186246
  • 1,857
  • 9
  • 29
  • 45

3 Answers3

2

Try it out! :) You'll find that neither of them can update the UI from a background thread, instead they need to use Control.BeginInvoke to invoke work on the UI thread, in which case they will execute in the order that they call BeginInvoke.

Oren
  • 3,273
  • 2
  • 19
  • 15
  • 1
    IIRC, some winforms versions will actually let you do it. Thinking <=2.0 maybe? (Of course, not that you *should* do it!) – Andrew Barber Jun 27 '13 at 06:12
  • Yup, looks like you're right - the WinForms that shipped in 2003 (I think that would be <2.0?) didn't have this restriction. See: http://msdn.microsoft.com/en-us/library/ms171728(v=vs.80).aspx for more info, well spotted! (That said, that's ancient history these days...) – Oren Jun 27 '13 at 06:43
1

Either of the thread will not be able to update the GUI.

You might get cross thread exception if you do not check 'InvokeRequired'.

if you still want these threads to access the same method, you can use Mutual Exclusion concept.

You can find more on Mutual Exclusion here.

This question on stack overflow also explain Mutual Exclusion in detail.

Community
  • 1
  • 1
jparthj
  • 1,606
  • 3
  • 20
  • 44
0

Invoke blocks until the thread has finished executing the update method.

However, this is actually only a message to the GUI thread to do this and it waits until it is done. Since the GUI thread can only execute one method at a time there is no real simultaneous execution. Nothing bad happens, but the behaviour may depend on the sequence of execution.

The sequence of execution, however, depends on which thread ever finished some guaranteed atomic (lock) operation.

JeffRSon
  • 10,404
  • 4
  • 26
  • 51