1. 程式人生 > >最簡單的使用執行緒的例子

最簡單的使用執行緒的例子

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;

namespace WinTest
{
    //執行緒示例 bwangel作
    public partial class Form1 : Form
    {
        delegate void showDelegate(int i, int v); //定義委託,引數根據需要定義

        showDelegate myShow; //宣告委託,相當於函式指標

        int Max = 1000000;
        Thread t = null;
        public Form1()
        {
            InitializeComponent();
        }

        protected void ShowText(int i, int v)
        {
            //顯示進度百分比和中間結果
            textBox1.Text = String.Format("{0:#}% => {1}",(double)i / Max * 100, v);
        }

        protected void DoingSomething()
        {
            int v = 0;
            for (int i = 0; i < Max; i++)
            {
                v += i;
                if (i % 100 == 0)
                {
                    Invoke(myShow, new object[] { i, v });
                }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            t = new Thread(new ThreadStart(DoingSomething));
            myShow = ShowText; //myShow這個函式指標指向實際要呼叫的函式
            t.Start();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            //別忘了在關掉視窗時檢查是否有沒有終止的執行緒。
            if (t != null && t.IsAlive)
                t.Abort();
        }
    }
}