private void button4_Click(object sender, EventArgs e)
{
DateTime dt1 = DateTime.Now;
if (textBox3.Text == "")
richTextBox3.Text += "2的0次方为1";
else
{
ManualResetEvent[] mr = new ManualResetEvent[int.Parse(textBox3.Text)];
for (int i = 1; i <= int.Parse(textBox3.Text); i++)
{
//int poolnum = i;
int temp = new int();
temp = i;
Control.CheckForIllegalCrossThreadCalls = false;
mr[temp - 1] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(delegate(object num)
{
long pre = 1;
for (int n = 1; n <= temp; n++)
{
Thread.Sleep(1);
pre *= 2;
}
richTextBox3.AppendText("2的" + temp.ToString() + "次方为: " + pre.ToString() + "\r\n");
mr[temp - 1].Set();
});
}
WaitHandle.WaitAll(mr);
}
DateTime dt2 = DateTime.Now;
label8.Text = (dt2 - dt1).TotalSeconds.ToString();
}
当我丢进去50个任务的时候,他就会漏掉几个数字不会计算。还有现在加了WaitHandle.WaitAll(mr);之后mr[temp-1].set()都执行不到,程序就会死等在那里不动了。高手指点一下啊。
http://www.cnblogs.com/clark159/archive/2012/03/22/2411438.html
此帖子介绍了怎么在线程池前加上隔离层,方法值得借鉴,只是本人还没有完全参悟,希望参透的网友们也帮我解释一下