欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#线程执行超时处理与并发线程数控制实例

程序员文章站 2023-12-17 13:47:16
本文实例讲述了c#线程执行超时处理与并发线程数控制的方法。分享给大家供大家参考。具体实现方法如下: 特别说明: 1、为了测试方便,这里对存储过程的执行是模拟的 2、这...

本文实例讲述了c#线程执行超时处理与并发线程数控制的方法。分享给大家供大家参考。具体实现方法如下:

特别说明:

1、为了测试方便,这里对存储过程的执行是模拟的

2、这里限制了并发执行存储过程的最大个数,但并没有对并发线程数进行控制,与文章标题略有不符,但程序稍做改动即可控制并发线程数

代码如下:

复制代码 代码如下:

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.data.oracleclient;
using system.diagnostics;
using system.io;
using system.serviceprocess;
using system.text;
using system.threading;
using system.timers;
using system.xml;
using dbutil;
using fqdservice.utils;

namespace fqdservice
{
    /// <summary>
    /// fqd服务
    /// </summary>
    partial class fqdservice : servicebase
    {
        #region 变量
        /// <summary>
        /// 存储过程配置文档
        /// </summary>
        public static xmldocument doc;
        /// <summary>
        /// 执行存储过程线程数锁
        /// </summary>
        public static object locktreadcount = new object();
        /// <summary>
        /// 执行存储过程超时时间
        /// </summary>
        public static int timeout = 1000;
        /// <summary>
        /// 等待执行存储过程时间间隔
        /// </summary>
        public static int interval = 100;
        /// <summary>
        /// 执行存储过程最大数
        /// </summary>
        public static int maxrunproccount = 5;
        /// <summary>
        /// 执行存储过程数
        /// </summary>
        public static int runproccount = 0;
        #endregion

        #region 构造函数
        public fqdservice()
        {
            initializecomponent();
        }
        #endregion

        #region 启动
        protected override void onstart(string[] args)
        {
            // todo: 在此处添加代码以启动服务。
            doc = xmlhelper.getxmldocument();
            system.timers.timer timer = new system.timers.timer(60 * 1000);
            timer.elapsed += new system.timers.elapsedeventhandler(runproc);
            timer.start();
        }
        #endregion

        #region 结束
        protected override void onstop()
        {
            // todo: 在此处添加代码以执行停止服务所需的关闭操作。
        }
        #endregion

        #region 执行存储过程
        /// <summary>
        /// 执行存储过程
        /// </summary>
        public void runproc(object sender, elapsedeventargs e)
        {
            try
            {
                random rnd = new random();
                xmlnode rootnode = doc.selectsinglenode("settings");

                foreach (xmlnode procnode in rootnode.childnodes) // 遍历proc
                {
                    string procname = procnode.selectsinglenode("name").innertext.trim();
                    string runtime = procnode.selectsinglenode("runtime").innertext.trim();

                    if (datetime.now.tostring("hh:mm") == "14:55")
                    {
                        bool finish = false; //存储过程是否执行完毕
                        thread thread = null;
                        thread = new thread(new parameterizedthreadstart(delegate(object obj)
                        {
                            #region 等待执行存储过程
                            lock (locktreadcount)
                            {
                                while (runproccount >= maxrunproccount)
                                {
                                    thread.sleep(interval);
                                }
                                runproccount++;
                            }
                            #endregion

                            #region 执行存储过程超时处理
                            thread threadtimer = new thread(new parameterizedthreadstart(delegate(object obj2)
                            {
                                thread.sleep(timeout);
                                if (finish == false)
                                {
                                    filelogger.writelog(string.format("存储过程{0}执行超时", procname));
                                    if (thread != null)
                                    {
                                        try
                                        {
                                            thread.abort();
                                        }
                                        catch (exception ex)
                                        {
                                            filelogger.writeerrorlog(string.format("存储过程{0}终止线程出错:{1}", procname, ex.message));
                                        }
                                    }
                                }
                            }));
                            threadtimer.start();
                            #endregion

                            #region 为执行存储过程准备参数
                            xmlnodelist paramlist = procnode.selectsinglenode("params").childnodes;
                            oracleparameter[] oracleparams = new oracleparameter[paramlist.count];
                            for (int i = 0; i < paramlist.count; i++) // 遍历param
                            {
                                xmlnode paramnode = paramlist[i];
                                string paramname = paramnode.selectsinglenode("name").innertext.trim();
                                string paramtype = paramnode.selectsinglenode("type").innertext.trim();
                                string paramvalue = paramnode.selectsinglenode("value").innertext.trim();

                                oracleparams[i] = new oracleparameter(paramname, enum.parse(typeof(oracletype), paramtype));
                                if ((oracletype)enum.parse(typeof(oracletype), paramtype) == oracletype.datetime)
                                {
                                    datetime now = datetime.now;
                                    string[] paramvaluearray = paramvalue.split(':');
                                    oracleparams[i].value = new datetime(now.year, now.month, now.day, int.parse(paramvaluearray[0]), int.parse(paramvaluearray[1]), int.parse(paramvaluearray[2]));
                                }
                                else
                                {
                                    oracleparams[i].value = paramvalue;
                                }
                            }
                            #endregion

                            try
                            {
                                try
                                {
                                    #region 执行存储过程
                                    filelogger.writelog(string.format("开始执行存储过程{0}", procname));

                                    //执行存储过程
                                    //oraclehelper.runprocedure(procname, oracleparams);

                                    //模拟执行存储过程
                                    thread.sleep(rnd.next(100, 1900));

                                    filelogger.writelog(string.format("存储过程{0}执行成功", procname));
                                    finish = true;
                                    #endregion
                                }
                                catch (exception ex)
                                {
                                    #region 执行存储过程失败日志
                                    stringbuilder sbparams = new stringbuilder();
                                    foreach (oracleparameter oracleparam in oracleparams)
                                    {
                                        sbparams.append(string.format("{0}:{1},", oracleparam.parametername, oracleparam.value.tostring()));
                                    }
                                    string strparams = "";
                                    if (sbparams.length > 0) strparams = sbparams.tostring(0, sbparams.length - 1);
                                    filelogger.writeerrorlog(string.format("存储过程执行失败{0}({1}):{2}", procname, strparams, ex.message));
                                    #endregion
                                }
                            }
                            catch
                            {
                                //捕获线程终止异常
                            }
                            finally
                            {
                                runproccount--;
                            }
                        }));
                        thread.start();
                    }
                }
            }
            catch (exception ex)
            {
                filelogger.writeerrorlog(ex.message);
            }
        }
        #endregion

    }
}

希望本文所述对大家的c#程序设计有所帮助。

上一篇:

下一篇: