不积跬步,无以至千里;不积小流,无以成江海

Our practice

不积跬步,无以至千里;不积小流,无以成江海

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

Threadpool线程池和泛型List<Thread>,实现同样功能的多线程的例子。

下载原代码 

Code:

using System;
using System.Threading;
using System.Collections.Generic;
public class OprateClass
{
    
public OprateClass( ManualResetEvent doneEvent)
    {
        _doneEvent 
= doneEvent;
    }

    
// Wrapper method for use with thread pool.
    public void ThreadPoolCallback(Object threadContext)
    {
        
int threadIndex = (int)threadContext;
        Console.WriteLine(
"Thread parameter:{0}", threadIndex);
        
        _doneEvent.Set();
    }

    
private ManualResetEvent _doneEvent;
}

public class ThreadPoolExample
{
    
static void Main()
    {
        
//1:the way used threadpool
        const int iCount = 10;
        
// One event is used for each object
        ManualResetEvent[] doneEvents = new ManualResetEvent[iCount];

        
// Configure and launch threads using ThreadPool:
        Console.WriteLine("launching {0} tasks", iCount);
        
for (int i = 0; i < iCount; i++)
        {
            doneEvents[i] 
= new ManualResetEvent(false);
            OprateClass f 
= new OprateClass(doneEvents[i]);
            ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
        }

        
// Wait for all threads in pool to calculation
        WaitHandle.WaitAll(doneEvents);
        Console.WriteLine(
"All calculations are complete.");

        
//2:the way used thread list,if need
        
        List
<Thread> ilistThread = new List<Thread>();
        
        
//the method which no paramaters
        
//ThreadStart idele = new ThreadStart(test);
        
//have parameters
        ParameterizedThreadStart idele = new ParameterizedThreadStart(test);

        Thread ithread 
= null;
        
for (int i = 0; i < 10; i++)
        {
            ithread 
= new Thread(idele);
            ithread.Start(i);
            ilistThread.Add(ithread);
        }

        
//wait all of thread finish
        foreach (Thread ith in ilistThread)
        {
            ith.Join();
        }
        
        Console.WriteLine(
"done");
        
    }

    
static void test(object i)
    {
        Console.WriteLine(i);
        Thread.Sleep(
20000);
    }
}

 

posted on 2008-08-26 23:31  英怀  阅读(898)  评论(0编辑  收藏  举报