Aborting Threads

  • Thread starter Thread starter AdrianDev
  • Start date Start date
A

AdrianDev

Hi,

I have a thread which I call like this:

// Allocate a new thread containing class with the host
getInfoThread git = new getInfoThread(host);

// Create the thread and call the Go method
new Thread(new ThreadStart (git.Go)).Start();

// Sleep for 5 seconds and abort the Thread if still active
//Thread,Sleep(5000);

// ????


I want to abort the thread if it has'nt completed after 5 seconds. But how
can I get a reference to the created Thread?


thanks,
 
Hi Adrian,

you should declare a thread in the scope of your class, so that
its members can access it an terminate/modify if necessary. The
Termination can be done inside a timer that also should catch
the ThreadAbort Exception. Simple try/catch directive.

Example:

public class SomeClass{

private Thread MyMemberVisibleThread;

private/public/protected void CreateMyThread(){

this.MyMemberVisibleThread = new Thread();
....
...
..

}

private void Timer5SecondsElapsedEventHandler(...){

try{

this.MyMemberVisibleThread.Abort();
//i am not sure whether it was abort() or terminate() to stop
the
//thread, check for the right method

}catch(Exception e1){

//Handle exception here

}

}


}

Regards

Kerem


--
 
I have a thread which I call like this: [...]

// Create the thread and call the Go method
new Thread(new ThreadStart (git.Go)).Start();

[...] I want to abort the thread if it has'nt completed after 5
seconds. But how
can I get a reference to the created Thread?

At the risk of helping you manage a thread in exactly the wrong way, I
will point out that you had a reference to the created thread when you
called "new Thread()". You just didn't bother to save it into some
variable.

But don't abort threads. If you need a way to have a thread terminated
after some period of time, you need to either build the timeout into
the thread logic itself, or you should provide a more general-purpose
signal to the thread to inform it to exit its processing (e.g. a
volatile flag).

Aborting a thread is no way to manage your code.

Pete
 

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

Similar Threads

about stopping threads and critical regions 1
stopping threads 2
Thread GC collection 6
Threading 8
threading 2
Why do ManagedThreadId start counting from 3 5
Thread 1
Problem with Threading in Win Forms 3

Back
Top