C# 多线程示例
using System;
using System.Windows.Forms;
using System.Threading;
namespace 多线程
{
delegate void SetValueCallback(int value);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ThreadStart(Foo));
t.Start();
}
private void Foo()
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(100);//间隔1秒继续下面的程序
SetProcessBarValue(i);//设置progressBar1的值
SetLabelValue(i);//设置label1的值
}
}
private void SetLabelValue(int value)
{
if (this.label1.InvokeRequired)
{
SetValueCallback d = new SetValueCallback(SetLabelValue);
this.Invoke(d, new object[] { value });
}
else
{
this.label1.Text = value.ToString() + '%';
}
}
private void SetProcessBarValue(int value)
{
// InvokeRequired required compares the thread ID of the calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.progressBar1.InvokeRequired)
{
SetValueCallback d = new SetValueCallback(SetProcessBarValue);
this.Invoke(d, new object[] { value });
}
else
{
this.progressBar1.Value = value;
}
}
private void button2_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(Fuu));
th.Start();
}
private void Fuu()
{
int m = 0;
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(50);//间隔0.05秒继续下面的程序
m = m + i;
}
MessageBox.Show(m.ToString());
}
//-----------------------------------------------------------------------------------------------
private void button1_Click(object sender, EventArgs e)
{
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
Thread t = new Thread(haha);
t.Start();
}
private void haha()
{
for (int i = 1; i < 10; i++)
{
textBox1.Text = i.ToString();
Thread.Sleep(1000);
}
}
}
}