当前位置:编程学习 > C#/ASP.NET >>

c#多线程测试代码

public class ThreadMulti
        {
 
            #region 变量
 
            public delegate void DelegateComplete();
            public delegate void DelegateWork(int taskindex, int threadindex);
 
            public DelegateComplete CompleteEvent;
            public DelegateWork WorkMethod;
 
            private Thread[] _threads;
            private bool[] _threadState;
            private int _taskCount = 0;
            private int _taskindex = 0;
            private int _threadCount = 20;//定义线程
          <span id="more-787"></span>
 
 
            #endregion
 
            public ThreadMulti(int taskcount)
            {
                _taskCount = taskcount;
            }
 
            public  ThreadMulti(int taskcount, int threadCount)
            {
                _taskCount = taskcount;
                _threadCount = threadCount;
            }
 
            #region 获取任务 参考了老羽http://www.cnblogs.com/michael-zhangyu/archive/2009/07/16/1524737.html 的博客
            private int GetTask()
            {
                lock (this)
                {
                    if (_taskindex < _taskCount)
                    {
                        _taskindex++;
                        return _taskindex;
                    }
                    else
                    {
                        return 0;
                    }
                }
            }
            #endregion
 
            #region Start
 
            /// <summary>
            /// 启动
            /// </summary>
            public void Start()
            {
                //采用Hawker(http://www.cnblogs.com/tietaren/)的建议,精简了很多
                _taskindex = 0;
                int num = _taskCount < _threadCount ? _taskCount : _threadCount;
                _threadState = new bool[num];
                _threads = new Thread[num];
 
                for (int n = 0; n < num; n++)
                {
                    _threadState[n] = false;
                    _threads[n] = new Thread(new ParameterizedThreadStart(Work));
                    _threads[n].Start(n);
                }
            }
 
            /// <summary>
            /// 结束线程
            /// </summary>
            public void Stop()
            {
                for (int i = 0; i < _threads.Length; i++)
                {
                    _threads[i].Abort();
                }
 
                //string s = "";
                //for (int j = 0; j < _threads.Length; j++)
                //{
                //    s +
补充:软件开发 , C# ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,