koumides
koumides

Reputation: 2504

Stopping Thread in C# while is in Unlimited wait mode

All,

I have a main thread which creates 10 threads all executing same method. Inside this method there is a connection to a message queue and each thread waits unlimited until a message arrives. However I need to have the functionality to tell the thread to die if I wanted to. How can I do it ?

Here is an example:

void ExecuteThread(){
//run some stuff
//listen to a message queue
//Here wait unlimited until a message arrives
}

How do I notify the above code which is in the unlimited wait command to stop the thread? I can't just abort it as I would it to gracefully disconnect from the queue.

Many Thanks, MK

}

Upvotes: 0

Views: 273

Answers (3)

Sunny Milenov
Sunny Milenov

Reputation: 22310

Do not wait unlimited, but use WaitOne with a timeout. Put that in a loop, which checks a flag for canceling. Then, from your main thread, you can signal threads to exit.

Something like (pseudo-code):

while (keepRunning)
{
   //wait 5 seconds for message
}

Upvotes: 1

Martin James
Martin James

Reputation: 24847

What sort of message queue? Can your main thread send a suicide message, (well, 10 suicide messages, or one suicide message with an internal count), on the queue?

Rgds, Martin

Upvotes: 1

DiableNoir
DiableNoir

Reputation: 644

Usually you have to create a waiting loop, which checks a shared variable. This variable says if the thread has to cancel it's operation.

WARNING: Do not create an infinity loop which checks the variable to often, this causes "busy waiting". You should wait for a message in the queue until a timeout arrives. After that timeout you can check your control variable and enter the waiting process for the queue again.

Upvotes: 0

Related Questions