C#的WinForm多线程应用
VS2005环境下,新建一个window窗体:命名多线程应用
完整代码:
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 多线程应用
{
public partial class Form1 : Form
{
public Form1()
{
CheckForIllegalCrossThreadCalls = false;//这种方法不好,最好用委托
InitializeComponent();
}
private void btnCalculate_Click(object sender, EventArgs e)
{
txtOutput.Text = "0";
lstMessage.Items.Clear();
int threadNumber = Convert.ToInt32(this.txtThreadNumber.Text);
for (int i = 1; i <= threadNumber; i++)
{
//ThreadStart threadStart = new ThreadStart(Add);
Thread thread = new Thread(new ThreadStart(this.Add));
thread.Name = i.ToString();
thread.Start();
}
}
private void Add()
{
DateTime beginTime = DateTime.Now;
long minValue = long.Parse(txtMinValue.Text);
long maxValue = long.Parse(txtMaxValue.Text);
int threadNumber = Convert.ToInt32(txtThreadNumber.Text);
int threadOrder = Convert.ToInt32(Thread.CurrentThread.Name);
long step=(maxValue-minValue+1)/threadNumber;
long beginValue=minValue+step*(threadOrder-1);
long endValue = beginValue + step;
long result = 0;
for (long i = beginValue; i < endValue; i++)
{
result += i;
}
lock(this)//线程同步锁
{
long sum = long.Parse(txtOutput.Text);
sum += result;
txtOutput.Text = sum.ToString();
}
DateTime endTime = DateTime.Now;
TimeSpan timeSpan = endTime - beginTime;
string message = "线程" + Thread.CurrentThread.Name + ":" + beginValue.ToString() + "到" + endValue.ToString() + ",耗时:" + timeSpan.TotalMilliseconds.ToString() + "毫秒";
this.lstMessage.Items.Add(message);
Thread.CurrentThread.Abort();
}
private void btnExit_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
总结:
多线程虽然可以提高程序的运行效率,但也不是绝对的,效率不会随线程数目增加呈现线性提高的,大家适当运用,另外下次我会用委托解决一些多线程的问题哦