.net c#线程超时解决方案

时间:2013-11-17 06:45:44
【文件属性】:

文件名称:.net c#线程超时解决方案

文件大小:1KB

文件格式:RAR

更新时间:2013-11-17 06:45:44

.net,c#,线程超

.net C#线程超时的解决方案,使用的时候在被调线程入口调用一下这个方法就可以。更多详细代码见附件 Report.RegisterThread(Report.GetCurrentWin32ThreadID(),Thread.CurrentThread); #region 获取当取线程的ThreadID [DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)] public static extern Int32 GetCurrentWin32ThreadID(); #endregion #region 登记访问任务子线程 ///

/// 访问任务子线程 /// public static Hashtable TaskThreadIDTable = Hashtable.Synchronized(new Hashtable()); private static int[] TaskThreadIDs { get { int[] IDs = new int[TaskThreadIDTable.Keys.Count]; TaskThreadIDTable.Keys.CopyTo(IDs, 0); return IDs; } } public static void RegisterThread(int _threadid, System.Threading.Thread thread) { if (!TaskThreadIDTable.ContainsKey(_threadid)) TaskThreadIDTable.Add(_threadid, thread); if (!ExitInvalidThreadLoopRunning) { Thread ExitInvalidThreadLoopThread = new Thread(new ThreadStart(ExitInvalidThreadLoop)); ExitInvalidThreadLoopThread.Priority = ThreadPriority.AboveNormal; ExitInvalidThreadLoopThread.Start(); } } #endregion #region 关闭,退出超时的用户线程 private static DateTime ExitInvalidThreadLoop_LastRunTime = DateTime.Now.Subtract(new TimeSpan(1, 0, 0, 0, 0)); private static bool ExitInvalidThreadLoopRunning { get { return DateTime.Now.Subtract(ExitInvalidThreadLoop_LastRunTime).TotalMinutes < 10; } } private static void ExitInvalidThreadLoop() { while (true) { ExitInvalidThread(); ExitInvalidThreadLoop_LastRunTime = DateTime.Now; //每10秒检查一次 Thread.Sleep(10 * 1000); } } private static void ExitInvalidThread() { #region 移除不存在的线程(比如线程运行完正常退出终了) Hashtable AllCurrentThreadIDs = new Hashtable(); ProcessThreadCollection ps = Process.GetCurrentProcess().Threads; foreach (ProcessThread t in ps) { AllCurrentThreadIDs.Add(t.Id, null); } int[] IDs = (int[])TaskThreadIDs.Clone(); foreach (int ID in IDs) { if (!AllCurrentThreadIDs.ContainsKey(ID)) TaskThreadIDTable.Remove(ID); } #endregion #region 退出超时的线程 foreach (ProcessThread t in ps) { //跳过非任务线程 if (!TaskThreadIDTable.ContainsKey(t.Id)) continue; //退出超时线程 TimeSpan ts = DateTime.Now.Subtract(t.StartTime); if (ts.TotalMinutes > 10) { try { Thread thread = (Thread)TaskThreadIDTable[t.Id]; thread.Abort(); } catch { } t.Dispose(); } } #endregion } #endregion


【文件预览】:
report.cs

网友评论