简体   繁体   English

使用Win.Forms控件在C#中进行多线程处理

[英]Multithreading in C# with Win.Forms control

I'm beginner in C#. 我是C#的初学者。 And i have problem with threads when i using win.forms. 当我使用win.forms时,我的线程有问题。 My application freezes. 我的申请冻结了。 What the problem with this code? 这段代码有什么问题? I'm using microsoft example from msdn . 我正在使用msdn的 microsoft示例。 Here's my code: 这是我的代码:

    delegate void SetTextCallback(object text);

    private void WriteString(object text)
    {
        // InvokeRequired required compares the thread ID of the 
        // calling thread to the thread ID of the creating thread. 
        // If these threads are different, it returns true. 
        if (this.textBox1.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(WriteString);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            for (int i = 0; i <= 1000; i++)
            {
                this.textBox1.Text = text.ToString();
            }
        }
    }

    private void button1_Click(object sender, EventArgs e)
    {

        Thread th_1 = new Thread(WriteString);
        Thread th_2 = new Thread(WriteString);
        Thread th_3 = new Thread(WriteString);
        Thread th_4 = new Thread(WriteString);

        th_1.Priority = ThreadPriority.Highest; // самый высокий
        th_2.Priority = ThreadPriority.BelowNormal; // выше среднего
        th_3.Priority = ThreadPriority.Normal; // средний
        th_4.Priority = ThreadPriority.Lowest; // низкий

        th_1.Start("1");
        th_2.Start("2");
        th_3.Start("3");
        th_4.Start("4");

        th_1.Join();
        th_2.Join();
        th_3.Join();
        th_4.Join();
    }

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() . 有一个死锁 - 当线程正在尝试使用阻塞Control.Invoke()向UI发送消息时,UI线程正在等待线程完成Thread.Join() Control.Invoke() Replacing the Invoke in the thread code by BeginInvoke() will make the deadlock go away 通过BeginInvoke()替换线程代码中的Invoke将使死锁消失

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

It freezes because of the Join calls. 它因Join调用而冻结。 Thread.Join() makes the current thread wait after another one is complete. Thread.Join()使当前线程在另一个完成后等待。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM