using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
class count
{
public count(int from, ManualResetEvent e)
{
_from = from;
_done_event = e;
}
private int _from;
private int _sum;
private ManualResetEvent _done_event;
public int docount(int _from)
{
int sum = 0;
for (int i = 0; i <= _from; i++)
{
sum += i;
}
return sum;
}
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("Thread {0} started", threadIndex);
_sum = docount(_from);
Console.WriteLine("Thread count result is {0}", _sum);
_done_event.Set();
}
}
public class ThreadPoolEx
{
static void Main()
{
const int times = 10;
ManualResetEvent[] mre = new ManualResetEvent[times];
Random r = new Random();
Console.WriteLine("Launch {0} tasks", times);
for (int i = 0; i < times; i++)
{
mre[i] = new ManualResetEvent(false);
count c = new count(r.Next(1, 1000), mre[i]);
ThreadPool.QueueUserWorkItem(c.ThreadPoolCallback, i);
}
WaitHandle.WaitAll(mre);
Console.WriteLine("All threads finished.");
}
}
C#线程池例子
最新推荐文章于 2024-08-09 20:31:50 发布