Click to See Complete Forum and Search --> : [RESOLVED] thread.Abort()


manzoor10
January 12th, 2009, 06:49 AM
Hey when I abort a thread it throws a ThreadAbortException right?

I catch it, it is re thrown again but the first time I catch it I call the function ResetAbort(), but the thread still aborts :(?

Help please....

Here's my code

// Threading.cpp : main project file.

#include "stdafx.h"

using namespace System;
using namespace System::Threading;

ref class MyThread
{
public:
static void ThreadFunc(Object ^Name);
};

void MyThread::ThreadFunc(Object ^Name)
{
Thread ^thr = Thread::CurrentThread;
try
{
for (int i = 0; i < 100; i++)
{
Console::WriteLine("{0} {1}", Name, i.ToString());
Thread::Sleep(10);
}
return;
}
catch (ThreadAbortException^)
{
Console::WriteLine("{0} Aborted", Name);
// Reset the abort so that the meoth will continue processing
thr->ResetAbort();
}
}


void main()
{
Console::WriteLine("Main Program Starts");

Thread ^thr1 = gcnew Thread(gcnew ParameterizedThreadStart(&MyThread::ThreadFunc));
Thread ^thr2 = gcnew Thread(gcnew ParameterizedThreadStart(&MyThread::ThreadFunc));

thr1->Start("Thread1");
thr2->Start("Thread2");

Thread::Sleep(20);
thr1->Abort();
Thread::Sleep(40);
thr2->Abort();

Console::WriteLine("Main Program Ends");
}

Alex F
January 12th, 2009, 10:20 AM
ResetAbort prevents thread aborting, but does not return code execution to the place where thread is aborted. In your case, thread execution continues with the code after catch block, and returns immediately. It is your responsibility to continue code execution if ResetAbort is called.

darwen
January 12th, 2009, 04:07 PM
Whoa ! Hold on there !

A thread should only be aborted when something serious goes wrong so correct behaviour in this case is to terminate the thread.

It should NOT be used to signal the thread - the usual signalling techniques should be used instead (events etc).

Nor should it be used to shut the thread down during normal operation - again you should have a signal which tells the thread to exit.

I just wanted to flag this point up. If you handle the thread abort exception how do you know whether the thread has been aborted by user code or by the .NET framework (e.g. on shutdown) ? The answer is you don't - so I'd strongly urge you not to go down this route.

Darwen.