您的位置:首页 > 编程语言 > C#

『C#基础』多线程笔记「四」线程池

2012-04-01 11:13 447 查看
现在到了关于多线最简单使用的最后一篇笔记。

无论从什么角度来看,每一项事物都应该有其所在的空间,而对于线程来说,线程池就是它所存在的空间,或者叫容器了。

接下来,看看这个线程池是如何使用的吧!

概念:

ManualResetEvent,通知一个或多个正在等待的线程已发生事件
ManualResetEvent.Set(),将事件状态设置为终止状态,允许一个或多个等待线程继续
ThreadPool.QueueUserWorkItem(…),将方法排入队列以便执行,并指定包含所用数据的对象。
WaitHandle.WaitAll(…),等待指定数组中的所有元素都收到信号

说明:

如果只是从代码的使用上看,将一个方法加入线程池,只需要一行ThreadPool.QueueUserWorkItem(<方法名>),再加上一个ManualResetEvent对象,并不要忘记在方法执行完毕后,Set一下,这个就可以了。

而对于更深一个层次的使用,就需要对CLR的远行机制以及对个人所要应用的项目特性进行了解、深入了。但是这明显不符合这篇笔记的主要目的,所以也就没必要去深究它了。

如果想要更深入的了解,就去看上面已经给出的几个大牛的文章吧~

代码:




「官方示例」// 版权所有(C) Microsoft Corporation。保留所有权利。
// 此代码的发布遵从
// Microsoft 公共许可(MS-PL,http://opensource.org/licenses/ms-pl.html)的条款。
//
//版权所有(C) Microsoft Corporation。保留所有权利。

using System;
using System.Threading;

// Fibonacci 类为使用辅助
// 线程执行长时间的 Fibonacci(N) 计算提供了一个接口。
// N 是为 Fibonacci 构造函数提供的,此外还提供了
// 操作完成时对象发出的事件信号。
// 然后,可以使用 FibOfN 属性来检索结果。
public class Fibonacci
{
public Fibonacci(int n, ManualResetEvent doneEvent)
{
_n = n;
_doneEvent = doneEvent;
}

// 供线程池使用的包装方法。
public void ThreadPoolCallback(Object threadContext)
{
int threadIndex = (int)threadContext;
Console.WriteLine("thread {0} started...", threadIndex);
_fibOfN = Calculate(_n);
Console.WriteLine("thread {0} result calculated...", threadIndex);
_doneEvent.Set();
}

// 计算第 N 个斐波纳契数的递归方法。
public int Calculate(int n)
{
if (n <= 1)
{
return n;
}
else
{
return Calculate(n - 1) + Calculate(n - 2);
}
}

public int N { get { return _n; } }
private int _n;

public int FibOfN { get { return _fibOfN; } }
private int _fibOfN;

ManualResetEvent _doneEvent;
}

public class ThreadPoolExample
{
static void Main()
{
const int FibonacciCalculations = 10;

// 每个 Fibonacci 对象使用一个事件
ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCalculations];
Fibonacci[] fibArray = new Fibonacci[FibonacciCalculations];
Random r = new Random();

// 使用 ThreadPool 配置和启动线程:
Console.WriteLine("launching {0} tasks...", FibonacciCalculations);
for (int i = 0; i < FibonacciCalculations; i++)
{
doneEvents[i] = new ManualResetEvent(false);
Fibonacci f = new Fibonacci(r.Next(20,40), doneEvents[i]);
fibArray[i] = f;
ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
}

// 等待池中的所有线程执行计算...
WaitHandle.WaitAll(doneEvents);
Console.WriteLine("Calculations complete.");

// 显示结果...
for (int i= 0; i<FibonacciCalculations; i++)
{
Fibonacci f = fibArray[i];
Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
}
}
}





「我的最简代码」        public override void operatThread()
{
int i =10;

WorkerClass[] worker = new WorkerClass[i];
ManualResetEvent[] events = new ManualResetEvent[i];

for (int j = 0; j < i; j++)
{
events[j] = new ManualResetEvent(false);    // 这里如果设置成true,则表示加入线程池之后,先处于等待状态
WorkerClass w= new WorkerClass("Thread", "Aaron");
worker[j] = w;

ThreadPool.QueueUserWorkItem(w.Do, j);
}

WaitHandle.WaitAll(events);
Console.WriteLine("Complete");
}





「我的最简代码」WorkerClass        public void Do(Object threadContext)
{
Console.WriteLine(Thread.CurrentThread.Name + this.WorkerName);
Console.WriteLine(threadContext.ToString());
}


成果:



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: