C#编程中如果想要实现多线程,我们可以自己新建Thread,也可以使用C#自带的ThreadPool(它提供一个线程池,该线程池可用于发送工作项、处理异步 I/O、代表其他线程等待以及处理计时器)。现在提供两个例子(控制台程序和窗体程序):
控制台程序:
- public class Fibonacci
- {
- public Fibonacci(int n, ManualResetEvent doneEvent)
- {
- _n = n;
- _doneEvent = doneEvent;
- }
- //Wrapper method for use with thread pool
- 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();
- }
- public int Calculate(int n)
- {
- if (n <= 1)
- {
- return n;
- }
- return Calculate(n - 1) + Calculate(n - 2);
- }
- public int N { get { return _n; } }
- public int FibOfN { get { return _fibOfN; } }
- private int _n;
- private int _fibOfN;
- private ManualResetEvent _doneEvent;
- }
- class Program
- {
- static void Main(string[] args)
- {
- const int FibonacciCaculations = 10;
- //One event is used for each Fibonacci object
- ManualResetEvent[] doneEvents = new ManualResetEvent[FibonacciCaculations];
- Fibonacci[] fibArray = new Fibonacci[FibonacciCaculations];
- Random r = new Random();
- //开始使用线程池
- Console.WriteLine("launching {0} tasks...", FibonacciCaculations);
- for (int i = 0; i < FibonacciCaculations; 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("All calculations are complete.");
- //Display the results
- for (int i = 0; i < FibonacciCaculations; i++)
- {
- Fibonacci f = fibArray[i];
- Console.WriteLine("Fibonacci({0}) = {1}", f.N, f.FibOfN);
- }
- Console.Read();
- }
- }
窗体程序:
阅读(4982) | 评论(0) | 转发(0) |