C# thread01

C# thread01

C# thread01

 
 


功能:

    01.單純利用執行緒每3秒改變表單的靜態成員變數
    02.利用delegate改變表單顯示
    03.最後在表單結束前結束執行緒
 

Code

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;//step 01

namespace CS_thread
{
	public partial class Form1 : Form
	{
		public static double m_dblcount;
		private Thread m_Thread = null;
		delegate void SetTextCallback(string text);
		public Form1()
		{
			InitializeComponent();
			m_dblcount = 0.0;
		}
		public void threadFun()
		{
			while (true)
			{
				Form1.m_dblcount += 1.0;
				String StrBuf;
				StrBuf=Convert.ToString(Form1.m_dblcount);
				SetText(StrBuf);
				Thread.Sleep(3000);
			}
		}
		private void SetText(string text)
		{
			if (this.textBox1.InvokeRequired)
			{
				SetTextCallback d = new SetTextCallback(SetText);
				this.Invoke(d, new object[] { text });
			}
			else
			{
				this.textBox1.Text = text;
			}
		}
		private void button1_Click(object sender, EventArgs e)
		{
			m_Thread = new Thread(new ThreadStart(threadFun));
			m_Thread.Start();
		}
		
		private void Form1_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (m_Thread.IsAlive)
			{
				m_Thread.Abort();
			}
		}
	}
}


發表迴響

你的電子郵件位址並不會被公開。 必要欄位標記為 *