Search code examples
c#.netmultithreadingthreadabortexception

Cannot wait process running until end


I have one aspx code behind page, that uses a process (p) to call an application (exe file) as following the code:

p.Start();
while(!p.HasExited)
{
    Thread.Sleep(2000);
}
p.Dispose();

The while loop to take waiting of 2s, but is always throwing the exception like below:

System.Threading.ThreadAbortException: Thread was being aborted.
   at System.Threading.Thread.SleepInternal(Int32 millisecondsTimeout)
   at Insyma.ContentUpdate.XmlReader.DoSleep()

At the statement Thread.Sleep(2000). So anybody can help me some solutions. Thanks so much,


Solution

  • Use AutoResetEvent

    class BasicWaitHandle
    {
       static EventWaitHandle _waitHandle = new AutoResetEvent (false);
       static void Main()
       {
           new Thread (Waiter).Start();        
           _waitHandle.WaitOne(); //wait for notification
           //Do operartion
       }
    
       static void Waiter()
       {
          //Do operations
          _waitHandle.Set(); //Unblock
       }
    }