当前位置:  编程技术>.net/c#/asp.net

winform开发使用通用多线程基类分享(以队列形式)

    来源: 互联网  发布时间:2014-10-25

    本文导语:    代码如下:///     /// 队列多线程,T 代表处理的单个类型~    ///     ///     public abstract class QueueThreadBase    {        #region 变量&属性        ///         /// 待处理结果        ///         private class PendingRe...

 

代码如下:

///
    /// 队列多线程,T 代表处理的单个类型~
    ///
    ///
    public abstract class QueueThreadBase
    {
        #region 变量&属性
        ///
        /// 待处理结果
        ///
        private class PendingResult
        {
            ///
            /// 待处理值
            ///
            public T PendingValue { get; set; }
            ///
            /// 是否有值
            ///
            public bool IsHad { get; set; }
        }
        ///
        /// 线程数
        ///
        public int ThreadCount
        {
            get { return this.m_ThreadCount; }
            set { this.m_ThreadCount = value; }
        }
        private int m_ThreadCount = 5;
        ///
        /// 取消=True
        ///
        public bool Cancel { get; set; }
        ///
        /// 线程列表
        ///
        List m_ThreadList;
        ///
        /// 完成队列个数
        ///
        private volatile int m_CompletedCount = 0;
        ///
        /// 队列总数
        ///
        private int m_QueueCount = 0;
        ///
        /// 全部完成锁
        ///
        private object m_AllCompletedLock = new object();
        ///
        /// 完成的线程数
        ///
        private int m_CompetedCount = 0;
        ///
        /// 队列锁
        ///
        private object m_PendingQueueLock = new object();
        private Queue m_InnerQueue;
        #endregion


        #region 事件相关
        ///
        /// 全部完成事件
        ///
        public event Action AllCompleted;
        ///
        /// 单个完成事件
        ///
        public event Action OneCompleted;
        ///
        /// 引发全部完成事件
        ///
        ///
        private void OnAllCompleted(CompetedEventArgs args)
        {
            if (AllCompleted != null)
            {
                try
                {
                    AllCompleted(args);//全部完成事件
                }
                catch { }
            }
        }
        ///
        /// 引发单个完成事件
        ///
        ///
        ///
        private void OnOneCompleted(T pendingValue, CompetedEventArgs args)
        {
            if (OneCompleted != null)
            {
                try
                {
                    OneCompleted(pendingValue, args);
                }
                catch { }

            }
        }
        #endregion

        #region 构造
        public QueueThreadBase(IEnumerable collection)
        {
            m_InnerQueue = new Queue(collection);
            this.m_QueueCount = m_InnerQueue.Count;
        }

        #endregion

        #region 主体
        ///
        /// 初始化线程
        ///
        private void InitThread()
        {
            m_ThreadList = new List();
            for (int i = 0; i < ThreadCount; i++)
            {
                Thread t = new Thread(new ThreadStart(InnerDoWork));
        m_ThreadList.Add(t);
                t.IsBackground = true;
                t.Start();
            }
        }
        ///
        /// 开始
        ///
        public void Start()
        {
            InitThread();
        }
        ///
        /// 线程工作
        ///
        private void InnerDoWork()
        {
            try
            {
                Exception doWorkEx = null;
                DoWorkResult doworkResult = DoWorkResult.ContinueThread;
                var t = CurrentPendingQueue;
                while (!this.Cancel && t.IsHad)
                {
                    try
                    {
                        doworkResult = DoWork(t.PendingValue);
                    }
                    catch (Exception ex)
                    {
                        doWorkEx = ex;
                    }
                    m_CompletedCount++;
                    int precent = m_CompletedCount * 100 / m_QueueCount;
                    OnOneCompleted(t.PendingValue, new CompetedEventArgs() { CompetedPrecent = precent, InnerException = doWorkEx });
                    if (doworkResult == DoWorkResult.AbortAllThread)
                    {
                        this.Cancel = true;
                        break;
                    }
                    else if (doworkResult == DoWorkResult.AbortCurrentThread)
                    {
                        break;
                    }
                    t = CurrentPendingQueue;
                }

                lock (m_AllCompletedLock)
                {
                    m_CompetedCount++;
                    if (m_CompetedCount == m_ThreadList.Count)
                    {
                        OnAllCompleted(new CompetedEventArgs() { CompetedPrecent = 100 });
                    }
                }

            }
            catch
            {
                throw;
            }
        }
        ///
        /// 子类重写
        ///
        ///
        ///
        protected virtual DoWorkResult DoWork(T pendingValue)
        {
            return DoWorkResult.ContinueThread;
        }
        ///
        /// 获取当前结果
        ///
        private PendingResult CurrentPendingQueue
        {
            get
            {
                lock (m_PendingQueueLock)
                {
                    PendingResult t = new PendingResult();
                    if (m_InnerQueue.Count != 0)
                    {
                        t.PendingValue = m_InnerQueue.Dequeue();
                        t.IsHad = true;
                    }
                    else
                    {
                        t.PendingValue = default(T);
                        t.IsHad = false;
                    }
                    return t;
                }
            }
        }

        #endregion

        #region 相关类&枚举
        ///
        /// dowork结果枚举
        ///
        public enum DoWorkResult
        {
            ///
            /// 继续运行,默认
            ///
            ContinueThread = 0,
            ///
            /// 终止当前线程
            ///
            AbortCurrentThread = 1,
            ///
            /// 终止全部线程
            ///
            AbortAllThread = 2
        }
        ///
        /// 完成事件数据
        ///
        public class CompetedEventArgs : EventArgs
        {
            public CompetedEventArgs()
            {

            }
            ///
            /// 完成百分率
            ///
            public int CompetedPrecent { get; set; }
            ///
            /// 异常信息
            ///
            public Exception InnerException { get; set; }
        }
        #endregion

    }

1.从构造函数来看,处理的是一个确定的列表.没错.这个多线程只能处理已经确定的列表,你是否会问.可不可以一边添加,一边处理呢?(呵呵,可以,请联系楼主,当然你也可以自己写,是吧?!)

代码如下:

public QueueThreadBase(IEnumerable collection)

2.提供撤销的功能

代码如下:

///
        /// 取消=True
        ///
        public bool Cancel { get; set; }

3.提供线程个数修改功能

代码如下:

///
        /// 线程数
        ///
        public int ThreadCount
        {
            get { return this.m_ThreadCount; }
            set { this.m_ThreadCount = value; }
        }

4.提供多种事件响应,如单个完成,全部完成的事件

代码如下:

///
        /// 全部完成事件
        ///
        public event Action AllCompleted;
        ///
        /// 单个完成事件
        ///
        public event Action OneCompleted;

5.提供完成的百分率

代码如下:

///
        /// 完成事件数据
        ///
        public class CompetedEventArgs : EventArgs
        {
            public CompetedEventArgs()
            {

            }
            ///
            /// 完成百分率
            ///
            public int CompetedPrecent { get; set; }
            ///
            /// 异常信息
            ///
            public Exception InnerException { get; set; }
        }

6.提供终止线程的方式,继续/单线程终止/全部终止

代码如下:

///
        /// dowork结果枚举
        ///
        public enum DoWorkResult
        {
            ///
            /// 继续运行,默认
            ///
            ContinueThread = 0,
            ///
            /// 终止当前线程
            ///
            AbortCurrentThread = 1,
            ///
            /// 终止全部线程
            ///
            AbortAllThread = 2
        }

你是否会问?怎么用呢?别急....请看

代码如下:

///
    /// 下载线程对了.
    ///
    public class DownLoadQueueThread:QueueThreadBase
    {
        ///
        ///
        ///
        /// 下载的列表ID
        public DownLoadQueueThread(IEnumerable list):base(list)
        {

        }
        ///
        /// 每次多线程都到这里来,处理多线程
        ///
        ///
        ///
        protected override DoWorkResult DoWork(int pendingID)
        {
            try
            {

                //..........多线程处理....
                return DoWorkResult.ContinueThread;//没有异常让线程继续跑..

            }
            catch (Exception)
            {

                return DoWorkResult.AbortCurrentThread;//有异常,可以终止当前线程.当然.也可以继续,
                //return  DoWorkResult.AbortAllThread; //特殊情况下 ,有异常终止所有的线程...
            }

            //return base.DoWork(pendingValue);
        }
    }

用法

总结:

多线程在什么时候都会用到.不用到是你不会用.多线程要一定的编程基础,如果你觉得有点难度,那你可以学习并且借鉴人家已有的东西.少走弯路,是我们程序员经历嗷嗷待哺后的心声.本文以交流态度和感恩心态,贡献给有需要的人们.


    
 
 
 
本站(WWW.)旨在分享和传播互联网科技相关的资讯和技术,将尽最大努力为读者提供更好的信息聚合和浏览方式。
本站(WWW.)站内文章除注明原创外,均为转载、整理或搜集自网络。欢迎任何形式的转载,转载请注明出处。












  • 相关文章推荐
  • .Net WInform开发笔记(二)Winform程序运行结构图及TCP协议在Winform中的应用
  • C# WinForm中禁止改变窗口大小的方法
  • WinForm相对路径的陷阱
  • c# Winform 全窗口拖动的代码
  • Winform实现抓取web页面内容的方法
  • WinForm实现关闭按钮不可用或隐藏的方法
  • 解读在C#中winform程序响应键盘事件的详解
  • 编程语言 iis7站长之家
  • C# Winform 整个窗口拖动的实现代码
  • WinForm下 TextBox只允许输入数字的小例子
  • C# WinForm程序完全退出的问题解决
  • C# WinForm窗体编程中处理数字的正确操作方法
  • C# Winform 让整个窗口都可以拖动
  • 使用C# Winform应用程序获取网页源文件的解决方法
  • c# 天气预报查询(winform方法)的实现代码(图文)
  • C# Winform 禁止用户调整ListView的列宽
  • C# winform编程中响应回车键的实现代码
  • C#中禁止Winform窗体关闭的实现方法
  • C# WinForm编程获取文件物理路径的方法
  • c#实现DataGridView控件隔行变色(winform)的代码


  • 站内导航:


    特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

    ©2012-2021,,E-mail:www_#163.com(请将#改为@)

    浙ICP备11055608号-3