程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#多線程編程實例 線程與窗體交互

C#多線程編程實例 線程與窗體交互

編輯:C#入門知識

C#多線程編程實例 線程與窗體交互


C#多線程編程實例 線程與窗體交互

/

代碼:

 

    public partial class Form1 : Form
    {
        //聲明線程數組
        Thread[] workThreads = new Thread[10];

        public Form1()
        {
            InitializeComponent();
        }

        //此委托允許異步的調用為Listbox添加Item
        delegate void AddItemCallback(string text);

        //這種方法演示如何在線程安全的模式下調用Windows窗體上的控件。
        private void AddItem(string text)
        {
            if (this.listBox1.InvokeRequired)
            {
                AddItemCallback d = new AddItemCallback(AddItem);
                this.Invoke(d, new object[] { text });
            }
            else
            {
                this.listBox1.Items.Add(text);
            }
        }

        //數據采集方法
        public void DataGet()
        {
            while (true)
            {
                AddItem(ok);
                Thread.Sleep(1000);
            }
            //如果此方法退出了,那麼這個線程也就退出了
        }

        /// 
        /// 啟動線程
        /// 
        ///
        ///
        private void button1_Click(object sender, EventArgs e)
        {
            //循環創建並啟動線程執行
            for (int i = 0; i < workThreads.Length; i++)
            {
                if (workThreads[i] == null)
                {
                    //如果線程不存在,則創建
                    workThreads[i] = new Thread(new ThreadStart(DataGet));
                    workThreads[i].Name = i.ToString();
                    workThreads[i].Start();
                }
                else
                {
                    //已經存在,如果沒有運行,則啟動
                    if (workThreads[i].ThreadState == ThreadState.Aborted || workThreads[i].ThreadState == ThreadState.Stopped)
                    {
                        workThreads[i] = new Thread(new ThreadStart(DataGet));
                        workThreads[i].Name = i.ToString();
                        workThreads[i].Start();
                    }else{
                        workThreads[i].Start();
                    }
                }
            }
        }

        /// 
        /// 停止線程
        /// 
        ///
        ///
        private void button2_Click(object sender, EventArgs e)
        {
            //循環停止線程執行
            for (int i = 0; i < workThreads.Length; i++)
            {
                //如果線程存在,並且狀態不是停止也不是終止的,則終止該線程
                if (workThreads[i] != null && workThreads[i].ThreadState != ThreadState.Stopped && workThreads[i].ThreadState != ThreadState.Aborted)
                {
                    workThreads[i].Abort();
                }
            }
        }
    }


 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved