Wednesday, 15 May 2013

How to make a loop to wait until background thread completes its execution(Multi Threading)?


some times we want to use the same thread  again and again inside the loop, but problem occurs when the thread is executing at background by that loop completes its execution, we get unexpected exceptions.

i too faced this probs, after struggling a lot i got the solution how to effectively use threads inside loop. so thought of posting to help others.

as in my previous blog i wrote how to create a thread How to create a Background running thread

suppose i had this thread that i want to call again inside loop.


Thread thread = new Thread(new ThreadStart(WorkThreadFunction));


now inside loop


for(int i = 0;i<10;i++)
   {   
     thread = new Thread(new ThreadStart(WorkThreadFunction));
         thread.IsBackground = true;
          thread.Start();
//now here i will use wait handle that will check that the previous process is alive or dead(means completed its execution or not)

        WaitHandle[] AWait = new WaitHandle[] { new AutoResetEvent(false) };
        while ( thread.IsAlive)
        {
            WaitHandle.WaitAny(AWait, 50, false);
            System.Windows.Forms.Application.DoEvents();
        } 
    }


if the thread is alive the loop will not move  the next item as while condition will be true everytime until thread is alive. and you can perform your form events and your GUI will not hang..

hope this helps ....

post your valuable comments





0 comments:

Post a Comment