C#线程封装

1、封装类:CThreadManage

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace ********************
{
    public class CThreadManage
    {

        /// <summary>
        /// 线程句柄
        /// </summary>
        private Thread hThread = null;

        /// <summary>
        /// 判断线程是否运行
        /// </summary>
        private Boolean bRuning = false;

        /// <summary>
        /// 判断线程单次运行是否结束
        /// </summary>
        private Boolean bRuningEnd = true;

        public Thread HThread
        {
            get
            {
                return hThread;
            }
            set
            {
                hThread = value;
            }
        }

        public Boolean BRuning
        {
            get
            {
                return bRuning;
            }
            set
            {
                bRuning = value;
            }
        }

        public Boolean BRuningEnd
        {
            get
            {
                return bRuningEnd;
            }
            set
            {
                bRuningEnd = value;
            }
        }

        public void CloseThread()
        {
            try
            {
                BRuning = false;
                if ( HThread != null )
                {
                    while ( !BRuningEnd )
                    {
                        Application.DoEvents();
                        Thread.Sleep(10);
                    }
                    HThread.Join();
                    HThread = null;
                }
            }
            catch (System.Exception )
            {

            }
        }
    }
}

2、启动线程

private CThreadManage ThoroughlyThread = null;

if (SyncListeningThread == null)
{
    SyncListeningThread = new CThreadManage();
    SyncListeningThread.BRuning = true;
    SyncListeningThread.BRuningEnd = true;
    SyncListeningThread.HThread = new Thread(new ThreadStart(SyncListeningFunc));
    SyncListeningThread.HThread.Start();
}
private void SyncListeningFunc()
{
    try
    {
        while (SyncListeningThread.BRuning)
        {
            SyncListeningThread.BRuningEnd = false;
            //func
            SyncListeningThread.BRuningEnd = true;
        }
    }
    catch (ThreadAbortException)
    {
        return;
    }
    catch (Exception)
    {
        SyncListeningFunc();
    }
}

3、关闭线程

if (SyncListeningThread != null)
{
    SyncListeningThread.CloseThread();
    SyncListeningThread = null;
}
分类:

发表回复