I am running a thread that does something, then sleeps for a while. If the program closes it continues to sleep to completion. How do I get it to abort immediatly, even if in the middle of sleeping?

void commThread::ThreadEntryPoint1()
{
     while(1)
     {
                //do work
	Sleep(15000);  //15 second sleep
     }
}

and in my mainform destructor which controls the thread:

~Form1()
		{
			if (components)
			{
				delete components;
			}

			if(Thread1->IsAlive)
			{
                                                                //Thread1->Interrupt();
				Thread1->Abort();
			}
		}

Thanks.

Recommended Answers

All 2 Replies

Instead of Sleep() you can use WaitForSingleObjectEx(), which lets you abort the sleep early.

I am running a thread that does something, then sleeps for a while. If the program closes it continues to sleep to completion. How do I get it to abort immediatly, even if in the middle of sleeping?

You may use TerminateThread function, it will terminate your thread immediatly, but it is bad practice. Right decision is to follow Ancient Dragon's recomendation and use some of synchronization objects instead -- for example event. Thread may sleep, waiting some event to be signaled, then awake and abort himself with proper resource cleanup, etc...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.