Problem with threads

  • Thread starter Thread starter Juan Carlos
  • Start date Start date
J

Juan Carlos

Hi

I have a method to create and start a thread, also I have
an event to know when this thread finish, but when a I
call the method two or more times, the event execute its
code this number of time for each thread that I have
created. For example If called the method twice, it
creates two threads and when one finish the event occurs
twice and when the another one finish happens the same.

What is wrong???

Regards
 
Hi Juan,
The problem is in your implementation. I bet you have somethig like this

class Foo
{
public event ThreadFinishedEventHandler ThreadFinished;
public StartThread()
{
Thread t = new Thread(new ThreadStart(ThreadProc));
t.Start();
}

void ThreadProc()
{
//Do some work

OnThreadFinished(....)
}

}

Then you create one object of this class (BTW this maight be your form or
control class as well as some designated class representing your thread).
Anyways, my guess is that you create only one instace of this class (your
form, control or special object )

and then you start each new thread like:

theOnlyThreadObject.ThreadFinished += new ThreadFinishedEventHandler(...)
theOnlyThreadObject.StartThread.

If I'm right then there the problem is. All your threads share the same
instance of ThreadFinishedEventHandler delegate for their event. Which means
that you chain all event handlers regardles of the thread you are about to
start. If you start 3 threads you will have 3 event handlers chained in the
event. Thus, when a thread finishes and fires its event your handler will be
called three times.

To avoid this you should create designated thread class that represents the
worker thread and has the event.
Then you have to create new object of this class each time you create a
thread.

class MyWorkerThread
{
public event ThreadFinishedEventHandler ThreadFinished;
private Thread mThread = null;
public Start()
{
if(mThread != null)
{
mThread = new Thread(new ThreadStart(ThreadProc));
t.Start();
}
}

void ThreadProc()
{
//Do some work

OnThreadFinished(....)
}

}

So when you want to start new thread you should do

MyWorkerThread thread = new MyWorkerThread()
thread.ThreadFinished += new ThreadFinishedEventHandler(...)
thread.Start();

HTH
B\rgds
100
 
* "Juan Carlos said:
I have a method to create and start a thread, also I have
an event to know when this thread finish, but when a I
call the method two or more times, the event execute its
code this number of time for each thread that I have
created. For example If called the method twice, it
creates two threads and when one finish the event occurs
twice and when the another one finish happens the same.

Post your code.
 
Back
Top