private static void ProcessEvent(eAction action, DelegateThread dt, ThreadContext tc) { if (dt != null) { lock (m_oLocker) { switch (action) { case eAction.Started: ExcpHelper.ThrowIf(m_diIdToContext.ContainsKey(tc.ManagedThreadId), "Thread is running already {0}", tc); ExcpHelper.ThrowIf(m_diNameToContext.ContainsKey(tc.ThreadName), "Thread is running already {0}", tc); m_diIdToContext.Add(tc.ManagedThreadId, tc); m_diNameToContext.Add(tc.ThreadName, tc); Debug.Assert(m_diIdToContext.Count == m_diNameToContext.Count); break; case eAction.Completed: ExcpHelper.ThrowIf(!m_diIdToContext.ContainsKey(tc.ManagedThreadId), "Thread is not running {0}", tc); ExcpHelper.ThrowIf(!m_diNameToContext.ContainsKey(tc.ThreadName), "Thread is not running {0}", tc); m_diIdToContext.Remove(tc.ManagedThreadId); m_diNameToContext.Remove(tc.ThreadName); Debug.Assert(m_diIdToContext.Count == m_diNameToContext.Count); break; case eAction.Error: Debug.Assert(m_diIdToContext.Count == m_diNameToContext.Count); break; default: Debug.Assert(false); break; } try { if (dt != null) { dt(tc); } } catch (Exception excp) { m_logger.Error(ExcpHelper.FormatException(excp, "ProcessEvent {0} ERROR for {1}:\r\n{2}\r\n{3}", action, tc, excp.Message, excp.StackTrace), excp); } } } }
private static void ThreadHelperThread(object objThreadContext) { ThreadContext tc = objThreadContext as ThreadContext; try { Debug.Assert(tc != null); tc.ManagedThreadId = Thread.CurrentThread.ManagedThreadId; m_logger.InfoFormat("{0} Started", tc); ProcessEvent(eAction.Started, ThreadStarted, tc); tc.SetRunning(true); try { tc.Method(tc); } catch (Exception excp) { tc.Error = excp; m_logger.ErrorFormat("ERROR in {0}:\r\n{1}\r\n{2}", excp, tc, excp.Message, excp.StackTrace); ProcessEvent(eAction.Error, ThreadError, tc); } m_logger.InfoFormat("{0} Completed", tc); tc.SetRunning(false); ProcessEvent(eAction.Completed, ThreadCompleted, tc); } catch (Exception excp) { tc.SetRunning(false); m_logger.Error(ExcpHelper.FormatException(excp, "ThreadHelperThread({0}) General ERROR", objThreadContext), excp); } }
public static ThreadContext RunThread(string sThreadName, DelegateThread dt, object objParam, ThreadPriority priority = ThreadPriority.Normal) { try { ThreadContext tc = null; lock (m_oLocker) { tc = m_diNameToContext.ContainsKey(sThreadName) ? m_diNameToContext[sThreadName] : null; } if (tc == null) { tc = new ThreadContext(sThreadName, dt, objParam); Thread thread = new Thread(ThreadHelperThread); thread.IsBackground = true; thread.Priority = priority; thread.Name = sThreadName; thread.Start(tc); } return(tc); } catch (Exception excp) { m_logger.Error(ExcpHelper.FormatException(excp, "RunThread('{0}', {1}, {2}) General ERROR", sThreadName, dt.Method, objParam), excp); } /* DK - ThreadPool is not suitable for long runnung items. * ThreadPool.QueueUserWorkItem(delegate(object obj) * { * }, objParam); */ return(null); }