程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#線程履行超時處置與並發線程數掌握實例

C#線程履行超時處置與並發線程數掌握實例

編輯:C#入門知識

C#線程履行超時處置與並發線程數掌握實例。本站提示廣大學習愛好者:(C#線程履行超時處置與並發線程數掌握實例)文章只能為提供參考,不一定能成為您想要的結果。以下是C#線程履行超時處置與並發線程數掌握實例正文


本文實例講述了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#法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved