private void Waiter(Object parentThread) { try { //Thread thrdTimer = new Thread(new ThreadStart(this.Timer)); //thrdTimer.Start(); //thrdTimer.Join(); //Thread.Sleep(m_timeout); int count = 0; int checkInterval = 50; //check if the parentThread is done every half a second. bool isTimeout = true; while (count < m_timeout) { if (((Thread)parentThread).IsAlive) { count += checkInterval; Thread.Sleep(checkInterval); } else { isTimeout = false; break; } } if (isTimeout) { if (((Thread)parentThread).IsAlive) { Exception timeoutEx = new Exception("Timeout!"); throw timeoutEx; } } } catch (Exception ex) { LogHelper.Error(ex); if (ex.Message.Equals("Timeout!")) { /*When a thread calls Abort on itself, the effect is similar to throwing * an exception; the ThreadAbortException happens immediately, and the result * is predictable. However, if one thread calls Abort on another thread, the abort * interrupts whatever code is running. There is a chance that a static constructor * could be aborted. In rare cases, this might prevent instances of that class from * being created in that application domain. In the .NET Framework versions 1.0 and * 1.1, there is a chance the thread could abort while a finally block is running, * in which case the finally block is aborted.*/ //lock (thisLock) //{ //} AbortThreadDelegate abd = new AbortThreadDelegate(AbortThread); abd.Invoke(parentThread); Thread.CurrentThread.Abort("Timeout!"); } } }
private void AbortThread(Object toBeAborted) { // do we need to switch threads? if (m_qbClient.InvokeRequired) { AbortThreadDelegate abd = new AbortThreadDelegate(AbortThread); object[] argu = { toBeAborted }; m_qbClient.BeginInvoke(abd, argu); return; } //somehow aborting a thread could be dangerous ((Thread)toBeAborted).Abort("Timeout!"); }