I have a question about multi-thread in C#.
In my program, I want to create some child threads to do some task and
meanwhile to hold the parent thread until all the child threads
terminate. What should I do?
Is the following code alright?
... ...
//Create an array of threads in above
int j = 0;
for (; j < 256; j++)
{
threadArr[j] = new Thread(new ThreadStart(MultiInsert5000));
threadArr[j].Start();
}
Thread.CurrentThread.Join();
// The following code is what I want to do after all the child threads
terminate
... ...
Please help me on this question. Your kindness will be appreciated.
http://www.codeproject.com/vb/net/ThreadDeath.asp
regards
Alberto
bool ThreadAlive = true;
while(ThreadAlive)
{
ThreadAlive = false;
for(int i = 0; i < 256; i++)
{
ThreadAlive = ThreadAlive || threadArr[i].IsAlive();
}
Thread.Sleep(0); //Placed in to free up the processor
}
//will reach here when all the threads are dead
Once again, this is a very simple way and there might be a better way.
> bool ThreadAlive = true;
> while(ThreadAlive)
> {
> ThreadAlive = false;
> for(int i = 0; i < 256; i++)
> {
> ThreadAlive = ThreadAlive || threadArr[i].IsAlive();
> }
> Thread.Sleep(0); //Placed in to free up the processor
> }
>
> //will reach here when all the threads are dead
>
based on the above code, I wrote a function like this:
void WaitForThreadsEnd(Thread [] arr)
{
bool bChildThAlive = true;
int index;
while(true)
{
for (index = 0; index < arr.Length; index++)
{
bChildThAlive = arr[index].IsAlive;
if (bChildThAlive)
{
// If there is one child thread still alive,
// make the parent thread sleep for 1 sec
Thread.Sleep(1000);
break;
}
}
if ((!bChildThAlive) && (index == arr.Length))
{
break;
}
}
}
> Once again, this is a very simple way and there might be a better way.
I also need a simple way :)
void WaitForThreadsEnd(Thread [] arr)
{
bool bChildThAlive = true;
while(bChildThAlive)
{
bChildThAlive = false;
for (index = 0; index < arr.Length; index++)
{
bChildThAlive = arr[index].IsAlive ||
bChildThAlive;
}
//this for loop will set the var bChildThAlive = true
if there is at least on thread alive
Thread.Sleep(0);
}
}