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