C#多线程同时执行时耗时比单个线程执行耗时会增加
运行结果:
源码:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
}
private object obj;
private void ceshiThread(Object obj)
{
Stopwatch sp = new Stopwatch();
sp.Restart();
int index = (int)obj;
int count = 0;
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 10000; j++)
{
int value = i * j;
count++;
}
}
sp.Stop();
textBox1.AppendText(string.Format("线程 {0} 执行次数 {1} ,总耗时 {2}", index, count, sp.ElapsedMilliseconds.ToString()));
textBox1.AppendText(Environment.NewLine);
}
private void button1_Click(object sender, EventArgs e)
{
//int a = 0;
//while (a < 100)
{
for (int i = 0; i < 4; i++)
{
Thread th = new Thread(ceshiThread);
th.IsBackground = true;
th.Start(i);
//Task t = new Task(() => ceshiThread(i));
//t.Start();
}
//a++;
//Thread.Sleep(5);
}
}
private void button2_Click(object sender, EventArgs e)
{
//Parallel.For(0, 4, (i) =>
//{
// ceshiThread(i);
//});
for (int i = 0; i < 4; i++)
{
ThreadPool.QueueUserWorkItem(ceshiThread, i);
}
//Task t = new Task(() => ceshiThread(0));
//t.Start();
}
private void button3_Click(object sender, EventArgs e)
{
//for (int i = 0; i < 100; i++)
//{
Thread th = new Thread(ceshiThread);
th.IsBackground = true;
th.Start(1);
//Thread.Sleep(200);
//}
//Thread th = new Thread(ceshiThread);
//th.IsBackground = true;
//th.Start(1);
}
}
}
新增委托后的源码:
private void ceshiThread(Object obj)
{
//用于时间测试
Stopwatch sp = new Stopwatch();
//开始测试时间
sp.Restart();
int index = (int)obj;
int count = 0;
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 10000; j++)
{
int value = i * j;
count++;
}
}
sp.Stop();
//线程委托
this.Invoke(new dvg(delegate () {
textBox1.AppendText(string.Format("线程 {0} 执行次数 {1} ,总耗时 {2}", index, count, sp.ElapsedMilliseconds.ToString()));
textBox1.AppendText(Environment.NewLine);
}));
}
private delegate void dvg(int index, int count, string millis);
private void dvgText(int index, int count, string millis)
{
textBox1.AppendText(string.Format("线程 {0} 执行次数 {1} ,总耗时 {2}", index, count, millis));
textBox1.AppendText(Environment.NewLine);
}
....
//线程委托
textBox1.Invoke(new dvg(this.dvgText), new object[] { index, count, sp.ElapsedMilliseconds.ToString() });
Control.CheckForIllegalCrossThreadCalls = false;不要设置,使用委托更新ui线程控件内容