Thinking about an answer to the question, and taking the hook from the discussion with @perozzo, who already posted a solution using Thread.Abort
, I was thinking of other ways to abort thread , things like semaphores by example, and I came across the interesting MVP article Joydip Kanjilal: My two cents on the Thread.Abort and Thread.Interrupt methods
In this article, it addresses some aspects of using Thread.Abort()
and Thread.Interrupt()
, and recalls that in thread we can handle this (detect that it was aborted) using ThreadAbortException
.
In the article he also remembers that neither method is thread-safe (if you do not know the concept, you can read more here: Thread safety ), that is, we have to treat the competition with shared resources.
The part that really caught the eye was that he, in his opinion, does not recommend abort thread using Thread.Abort()
for example (in free translation):
My honest answer is that you should never use any of these
methods to terminate a thread . It is advisable not to use the Thread.Abort
or Thread.Interrupt to terminate a thread - you should instead,
take advantage of synchronization objects (such as WaitHandles or
Semaphores ) and quit "gracefully" the threads
is using.
Another idea he mentions is to use a variable boolean volatile
shared with the thread , which is checked to continue thread execution in> and can be altered by another thread , thus making it gracefully shut down as it mentions.
An example code from the C # Programming Guide :
// variável de controle
internal volatile bool _shouldStop;
// método para "parar a thread", que vai setar a variável
public void RequestStop()
{
_shouldStop = true;
}
// método da thread
public void DoWork()
{
while (!_shouldStop)
{
Console.WriteLine("worker thread: working...");
}
Console.WriteLine("worker thread: terminating gracefully.");
}
Another way to do something similar is by using an object CancellationTokenSource . This piece of code (based on In MSDN ) shows an example:
var cts = new CancellationTokenSource();
void ExecutarThread()
{
// inicia o token
cts = new CancellationTokenSource();
// Passa o token para a thread
Task.Run(() => DoWork(cts.Token), cts.Token);
}
void CancelarThread()
{
cts.Cancel();
cts.Dispose();
}
void DoWork(CancellationToken token)
{
while (alguma_condicao_de_loop)
{
// verifica se foi cancelado
if (token.IsCancellationRequested) {
Console.WriteLine("I was canceled while running.");
// sai e trata
break;
// ou dispara uma exception tratada pelo token
token.ThrowIfCancellationRequested();
}
}
}
Codes are examples adapted to demonstrate the functionality, probably need some adjustment to work in each scenario, but are other ways to try to abort a thread .