ThreadPool用法
来源:互联网 发布:wow客户端优化怎样用 编辑:程序博客网 时间:2024/05/03 14:58
使用ThreadPool实现多线程执行
class Program
{
static void Main(string[] args)
{
List<BaseWorker> list = new List<BaseWorker>();
BaseWorker worker = null;
for (int i = 0; i < 100; i++)
{
worker = new BaseWorker(i.ToString());
list.Add(worker);
}
ParallelProcessor.ExecuteParallel(list.ToArray());
Console.WriteLine("---end");
Console.Read();
}
}
interface IParallelWorker
{
void Run();
}
internal class BaseWorker : IParallelWorker
{
private string _flag;
public BaseWorker(string flag)
{
_flag = flag;
}
public void Run()
{
Console.WriteLine(_flag+" Start");
Console.WriteLine(_flag + " End" );
}
}
internal class ParallelProcessor
{
public static void ExecuteParallel(IParallelWorker[] methods)
{
int account = methods.Length;
if (methods.Length > 0)
{
// Initialize the reset events to keep track of completed threads
ManualResetEvent reset=new ManualResetEvent(false);
// Launch each method in it's own thread
for (int i = 0; i < methods.Length; i++)
{
//resetEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object index)
{
try
{
int methodIndex = (int)index;
// Execute the method
methods[methodIndex].Run();
}
catch (Exception)
{
}
finally
{
if (Interlocked.Decrement(ref account) == 0)
{
// Tell the calling thread that we're done
reset.Set();
}
}
}), i);
}
// Wait for all threads to execute
reset.WaitOne();
}
}
}
- ThreadPool用法
- ThreadPool.QueueUserWorkItem 用法
- ThreadPool用法实例
- python里threadpool用法
- ThreadPool用法与优势
- ThreadPool用法与优势
- ThreadPool用法和示例
- ThreadPool用法与优势
- C# ThreadPool的简单用法
- ThreadPool的用法与优势
- threadpool
- ThreadPool
- threadPool
- threadpool
- ThreadPool
- threadpool
- threadpool
- ThreadPool
- vsftpd的553 Could not create file 错误
- javascript中的float运算精度
- StateMachineWorkflowInstance 类
- alsa 音频库的移植
- 完成端口
- ThreadPool用法
- oracle中连接单引号
- J2ME 记录管理系统
- Why all of the passengers ran away?
- C++左值与右值之间共同与不同点解析
- 因特网控制报文协议ICMP
- S2SH配置过程 详解(2)
- UNIX环境高级编程学习之第十五章进程间通信 - 通过有名管道(命名管道)实现进程间通信
- S2SH配置过程 详解(3)