时间:2021-12-12 11:57:10 | 栏目:.NET代码 | 点击:次
本文实例讲述了C#线程执行超时处理与并发线程数控制的方法。分享给大家供大家参考。具体实现方法如下:
特别说明:
1、为了测试方便,这里对存储过程的执行是模拟的
2、这里限制了并发执行存储过程的最大个数,但并没有对并发线程数进行控制,与文章标题略有不符,但程序稍做改动即可控制并发线程数
代码如下:
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#程序设计有所帮助。