惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

云风的 BLOG
云风的 BLOG
IT之家
IT之家
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
V
Visual Studio Blog
博客园 - 司徒正美
美团技术团队
Last Week in AI
Last Week in AI
月光博客
月光博客
博客园 - 叶小钗
MongoDB | Blog
MongoDB | Blog
U
Unit 42
T
Tailwind CSS Blog
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
H
Hackread – Cybersecurity News, Data Breaches, AI and More
酷 壳 – CoolShell
酷 壳 – CoolShell
Google DeepMind News
Google DeepMind News
H
Help Net Security
Hugging Face - Blog
Hugging Face - Blog
爱范儿
爱范儿
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
N
Netflix TechBlog - Medium
B
Blog RSS Feed
大猫的无限游戏
大猫的无限游戏
aimingoo的专栏
aimingoo的专栏
A
About on SuperTechFans
Y
Y Combinator Blog
罗磊的独立博客
D
DataBreaches.Net
有赞技术团队
有赞技术团队
MyScale Blog
MyScale Blog
博客园_首页
博客园 - 三生石上(FineUI控件)
G
Google Developers Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
雷峰网
雷峰网
博客园 - 【当耐特】
Engineering at Meta
Engineering at Meta
博客园 - Franky
M
MIT News - Artificial intelligence
B
Blog
The Cloudflare Blog
Apple Machine Learning Research
Apple Machine Learning Research
I
InfoQ
S
SegmentFault 最新的问题
F
Fortinet All Blogs
阮一峰的网络日志
阮一峰的网络日志
Stack Overflow Blog
Stack Overflow Blog
Microsoft Security Blog
Microsoft Security Blog

博客园 - 老羽

推荐AspNetPager分页控件 SqlServer2005中分页代码测试 WM中实现Splash动画效果 自定义合并多文件协议设计 JScript中Date.getTime转.Net中的DateTime .net中处理C/C++中的位域 POOM(Pocket Outlook Object Model)开发介绍及应用(转) GPRS管理与创建APN拨号连接 WM中电话相关的技巧 - 老羽 - 博客园 一道面试题题解 【转】Windows Mobile控制面板程序 [转]Windows Mobile上的服务程序 Smartphone2003开发总结一:Form总结 C++常用技巧一(整理收集) [转]CString,string,char*的综合比较 [转] C++ Windows字符和字符指针类型 [转]C++ int,char,string,CString类型转换(整理总结) C++字符串函数详解[转] Smartphone2003中实现焦点在ListView控件与其它控件中切换
多线程执行多任务的DEMO
老羽 · 2009-07-16 · via 博客园 - 老羽

2009-07-16 12:55  老羽  阅读(2746)  评论()    收藏  举报

应朋友之邀,写了一个多线程执行多任务的例子。这个场景应用比较普遍,

比如多个线程下载多个文件,比如3个线程下载10个文件,比如10个线程执行1000条任务队列;

Demo代码如下:

public partial class Form1 : Form
    {
        private ThreadProxy _threadsProxy = null;
        ExpressCollection list = new ExpressCollection();

        public Form1()
        {
            InitializeComponent();

            _threadsProxy = new ThreadProxy(3, list);
            _threadsProxy.ExpressComputed += new EventHandler<ExpressComputedEventArgs>(_threadsProxy_ExpressComputed);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            list.Clear();
            _threadsProxy.Stop();
            list.Add(new Express(1, 1));
            list.Add(new Express(1, 2));
            list.Add(new Express(1, 3));
            list.Add(new Express(1, 4));
            list.Add(new Express(1, 5));
            list.Add(new Express(1, 6));
            list.Add(new Express(1, 7));
            list.Add(new Express(1, 8));
            list.Add(new Express(1, 9));
            list.Add(new Express(1, 10));
            list.Add(new Express(1, 11));
            list.Add(new Express(1, 12));
            list.Add(new Express(1, 13));
            list.Add(new Express(1, 14));
            Console.WriteLine("启动线程...........................");
            _threadsProxy.Run();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (_threadsProxy != null)
            {
                Console.WriteLine("测试暂停...........................");
                _threadsProxy.Stop();
            }
        }

        void _threadsProxy_ExpressComputed(object sender, ExpressComputedEventArgs e)
        {
            Console.WriteLine(string.Format("ThreadID:{0}  {1} + {2} = {3}", Thread.CurrentThread.ManagedThreadId, e.Express.A, e.Express.B, e.Result));
        }
    }
    public class ThreadProxy : IDisposable
    {
        private int _threadCount = 1;
        ExpressCollection _list;
        private Thread[] _threads = null;
        private bool _isRun = false;

        public ThreadProxy(ExpressCollection list)
        {
            _list = list;
        }

        public ThreadProxy(int threadCount, ExpressCollection list)
            : this(list)
        {
            _threadCount = threadCount;
            _threads = CreateThreadCollection();
        }

        public void Run()
        {
            if (!_isRun && _list != null && _list.Count>0)
            {
                _isRun = true;
                for (int i = 0; i < _threadCount; i++)
                {
                    _threads[i] = new Thread(new ThreadStart(ThreadInvoke));
                    _threads[i].IsBackground = true;
                    _threads[i].Start();
                }
            }
        }

        protected virtual Thread[] CreateThreadCollection()
        {
            return new Thread[_threadCount];
        }

        public void Stop()
        {
            _isRun = false;
        }

        private void ThreadInvoke()
        {
            try
            {
                while (_isRun)
                {
                    Express express = _list.GetNext();
                    if (express != null)
                    {
                        int result = express.A + express.B;
                        OnExpressComputed(result, express);
                        //do something
                        Thread.Sleep(1000);//测试暂停
                    }
                    else
                    {
                        break;
                    }
                }
            }
            catch (ThreadAbortException)
            {
                Thread.ResetAbort();
                return;
            }
            catch (Exception)
            {
                //记录日志
            }
        }

        public event EventHandler<ExpressComputedEventArgs> ExpressComputed;

        protected virtual void OnExpressComputed(int result ,Express express)
        {
            if (ExpressComputed != null)
            {
                ExpressComputed(this, new ExpressComputedEventArgs(result,express));
            }
        }

        #region IDisposable 成员

        public void Dispose()
        {
            _isRun = false;
            if (_threads != null)
            {
                _threads = null;
            }
        }

        #endregion
    }

    public class ExpressComputedEventArgs : EventArgs
    {
        private int result;

        public int Result
        {
            get { return result; }
            set { result = value; }
        }

        public ExpressComputedEventArgs(int result , Express express)
        {
            this.result = result;
            this.express = express;
        }

        private Express express;

        public Express Express
        {
            get { return express; }
            set { express = value; }
        }
    }
 
public class BaseCollection<T> : List<T>
    {
        protected readonly object _lockObj = new object();

        private int index = 0;
        public virtual T GetNext()
        {
            T result = default(T);
            if (this.Count > 0 && index < Count)
            {
                lock (_lockObj)
                {
                    result = this[index];
                    index++;
                }
            }
            return result;
        }

        public new void Add(T item)
        {
            lock (_lockObj)
            {
                base.Add(item);
            }
        }

        public new void Clear()
        {
            lock (_lockObj)
            {
                index = 0;
                base.Clear();
            }
        }
    }
public class Express
    {
        private int _a;

        public int A
        {
            get { return _a; }
            set { _a = value; }
        }

        private int _b;

        public int B
        {
            get { return _b; }
            set { _b = value; }
        }

        public Express(int a, int b)
        {
            _a = a;
            _b = b;
        }
    }
public class ExpressCollection : BaseCollection<Express>
   {

   }