1

私はC#の初心者です。また、win.formsを使用すると、スレッドに問題が発生します。アプリケーションがフリーズします。このコードの何が問題になっていますか?私はmsdnのマイクロソフトの例を使用しています。これが私のコードです:

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

2 に答える 2

4

Thread.Join()デッドロックがあります-ワーカースレッドがブロッキングを使用してUIにメッセージを送信しようとしている間、UIスレッドはスレッドが完了するのを待機していますControl.Invoke()。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();
    }
于 2013-03-22T19:43:08.233 に答える
0

Join呼び出しのためにフリーズします。Thread.Join()は、別のスレッドが完了した後、現在のスレッドを待機させます。

于 2013-03-22T19:45:02.093 に答える