calling exit thread from other thread ?

D

Daylor

hi.
i have main thread , and 2 others thread (t1 ,t2 for example)

how can i call from the main thread, to tell t1 to exit his thread ?
(calling application.exitthread from main thread, in method of class created
on t1 ,will call exitthread to the main thread)

what is the simple way to do that ?
 
R

Ryan Byington

There is a couple of ways you can handle this.

One you can you call t1.Abort() or t2.Abort() and the thread will exit.
This is a pretty abrupt shutdown of the thread and may leave some of the
references the thread has in an undefined state.

The other option is to have some property that the helper thread checks and
when set to true by the main thread the helper thread exits.

In the main thread do the following:

MyWorkerThread myWorker = new MyWorkerThread()
Thread t = new Thread(new ThreadStart(myWorker.DoSomeWork));
t.Start();

/*
DO SOME STUFF
*/

myWorker.ExitThread = true;
/* The thread should now exit on the next iteration */


public class MyWorkerThread
{
public bool ExitThread = false;

public void DoSomeWork()
{
while(true) {
if(ExitThread) {
return;
}
/* DO SOME WORK HERE */
}
}
}

Thanks,

Ryan Byington [MS]

This posting is provided "AS IS" with no warranties, and confers no rights.
Use of included script samples are subject to the terms specified at
http://www.microsoft.com/info/cpyright.htm.


--------------------
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top