Multithreading in C# with Win.Forms control

后端 未结 2 1212
醉梦人生
醉梦人生 2021-01-25 13:54

I\'m beginner in C#. And i have problem with threads when i using win.forms. My application freezes. What the problem with this code? I\'m using microsoft example from msdn. Her

2条回答
  •  北恋
    北恋 (楼主)
    2021-01-25 14:11

    There is a deadlock - UI thread is waiting for threads to complete with Thread.Join() while the worker threads are trying to send a message to UI using blocking Control.Invoke(). Replacing the Invoke in the thread code by BeginInvoke() will make the deadlock go away

     if (this.textBox1.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(WriteString);
            // BeginInvoke posts message to UI thread asyncronously
            this.BeginInvoke(d, new object[] { text }); 
        }
        else
        {
            this.textBox1.Text = text.ToString();
        }
    

提交回复
热议问题