用線程和不用線程的區別(代碼說明)

來源:互聯網
上載者:User

在這裡 有用線程和不用線程兩種。

1點“用線程”按鈕。在左邊textbox會出現目前時間毫秒不斷更新。因為用了線程所以這件事他是獨立一個線程去做的。我可以同時做別的操作去。比如拖動視窗。

2 點”不用線程”按鈕。左邊textbox 會出現0到5000的數字跳動。但這時我不能對視窗做任何操作。因為程式只有一個線程,都被0加到5000的for迴圈佔用了。我不能做別的事了。

可以看出,如果有一個操作很耗時間,在執行這個操作時,我又要做別的操作。這個時候就可以使用一個多線程。

using System.Threading;
namespace cacheDemo1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    Thread threadShowTime;
    private void ShowTime()
    {
        int i = 0;
        while (i < 100000)
        {
            string str = string.Format("{0}.{1}", DateTime.Now.ToLongTimeString(), DateTime.Now.Millisecond);
            WriteInTxt(str); //如果線上程中要操作控制項,那就必須要用委託回調的方法
            Application.DoEvents();//讓每次更新的時間顯示到介面上
            i++;
        }
        threadShowTime.Join();
    }
    delegate void WriteInTxtCallBack(string str);
    private void WriteInTxt(string str)
    {
        if (this.textBox1.InvokeRequired)
        {
            WriteInTxtCallBack writeTxtCallBack = new WriteInTxtCallBack(WriteInTxt);
            this.Invoke(writeTxtCallBack, new object[] { str });
        }
        else
        {
            this.textBox1.Text = str;
        }
    }
    private void button1_Click(object sender, EventArgs e)
    {
        //同一個線程不能多次start,再重新new一個。
        threadShowTime = new Thread(new ThreadStart(ShowTime));
        threadShowTime.IsBackground = true;
        threadShowTime.Start();
    }
    private void button2_Click(object sender, EventArgs e)
    {
        for (int i = 0; i < 5000; i++)
        {
            textBox4.Text = i.ToString();
            Application.DoEvents(); //使i數字即時顯示到視窗上
        }
    }
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.