设为首页 加入收藏

TOP

自定义线程池-c#的简单实现
2014-11-23 22:51:33 】 浏览:437
Tags:定义 线程 简单 实现

  由二部分组成,一个线程管理类ThreadManager,一个线程类MyThread Test类是用来测试的


  参考了以下资料:
  http://tech.ccidnet.com/pub/disp/Article columnID=294&articleID=33440&pageNO=1
  http://soft.yesky.com/SoftChannel/72342371961929728/20041013/1863707.shtml


  下面是代码,希望大家提出更好的建议:


  1.ThreadManager.cs


  using System;


  using System.Threading;


  using System.Collections;


  namespace CustomThreadPool


  {


  ///



  public class ThreadManager


  {


  private static ArrayList threadList = new ArrayList(); //线程列表,静态


  //不允许创建实例


  private ThreadManager()


  {


  }


  ///



  /// 委托实例


  /// 传递给回调方法的参数


  /// 当没有可用的线程时的等待时间,以毫秒为单位


  ///


  public static bool QueueUserWorkItem(WaitCallback waitCallback, Object obj, int timeOut)


  {


  //锁住共享资源,实现线程安全


  lock(threadList)


  {


  try


  {


  //如果线程列表为空,填充线程列表


  if (threadList.Count == 0)


  {


  InitThreadList();


  }


  long startTime = DateTime.Now.Ticks;


  do


  {


  //遍历线程列表,找出可用的线程


  foreach(MyThread myThread in threadList)


  {


  //线程为空,需要创建线程


  if (myThread.T == null)


  {


  myThread.Start(waitCallback, obj, false);


  return true;


  }


  else if (myThread.T.ThreadState == ThreadState.Suspended)


  {//线程为挂起状态,唤醒线程


  myThread.Start(waitCallback, obj, true);


  return true;


  }


  }


  //在线程 Sleep 前释放锁


  Monitor.PulseAll(threadList);


  Thread.Sleep(500);


  }while (((DateTime.Now.Ticks - startTime) / 10000) < timeOut);


  }


  finally


  {


  Monitor.Exit(threadList);


  }


  }


  return false;


  }


  //使用 MyThread 对象填充线程列表,注意,这个时候线程并没有启动


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇C#中调用WindowsAPI的要点 下一篇C#中使用反射的性能分析

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目