aborting a thread in C#

G

Guest

Hi..
Am trying to kill a thread that is performing a method using abort call. But
the thread until reaches a "safe point" doesnt get killed. Is there any
method of killing a thread instantaneously.

here's what the method on which the thread is working on trying to do.

public static void ThreadMethod()
{
Socket mysocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.IP);
mysocket.Connect(remoteEndPoint);
}
I want to kill the thread in 20ms.
 
D

David Levine

Using abort from another thread is a bad way of killing a thread - there are
all kinds of side effects that can occur from asynchronously aborting a
thread. A thread can Abort itself usually without a problem because that
makes it synchronous. A better approach is to set a flag or an event
indicating that you want to cancel an operation and use program logic to
handle it yourself.

The Abort does not get delivered instantly to the thread. The thread must be
in an alertable wait state before the abort will be injected. Calling abort
sets the state of the thread to AbortRequested, but the CLR wont actually
deliver the abort until it is able to do so. The mechanism used to deliver
the abort is subject to change but I believe the current version schedules
an APC to the target thread, and once delivered it raises the abort
exception.

..NET is not a realtime system and there simply is no way to guarantee that
anything will happen within a given time frame, let alone that a thread will
be aborted; period. If you have strict timing requirements, such as aborting
a thread within 20 mS, then .NET is the wrong OS to use.

For your purposes there may be a way of canceling the Connect request. You
should be able to use the async form of Connect and simply ignore the
results if you want to cancel the operation. I haven't used this class so I
am not familiar with its options.
 

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