How to abort a Task like aborting a Thread (Thread.Abort method)?
- You shouldn't use Thread.Abort()
- Tasks can be Cancelled but not aborted.
The Thread.Abort() method is (severely) deprecated.
Both Threads and Tasks should cooperate when being stopped, otherwise you run the risk of leaving the system in a unstable/undefined state.
If you do need to run a Process and kill it from the outside, the only safe option is to run it in a separate AppDomain.
This answer is about .net 3.5 and earlier.
Thread-abort handling has been improved since then, a.o. by changing the way finally blocks work.
But Thread.Abort is still a suspect solution that you should always try to avoid.
And in .net Core (.net 5+) Thread.Abort() will now throw a PlatformNotSupportedException
.
Kind of underscoring the 'deprecated' point.
How to cancle a task on Thread.Abort()
You can handle ThreadAbortException to deal with cleanup, including aborting other threads if ncessary.
void MyThreadProc()
{
try
{
//Do interesting things
}
catch ( ThreadAbortException e )
{
childThread.Abort();
}
}
How do I abort/cancel TPL Tasks?
You can't. Tasks use background threads from the thread pool. Also canceling threads using the Abort method is not recommended. You may take a look at the following blog post which explains a proper way of canceling tasks using cancellation tokens. Here's an example:
class Program
{
static void Main()
{
var ts = new CancellationTokenSource();
CancellationToken ct = ts.Token;
Task.Factory.StartNew(() =>
{
while (true)
{
// do some heavy work here
Thread.Sleep(100);
if (ct.IsCancellationRequested)
{
// another thread decided to cancel
Console.WriteLine("task canceled");
break;
}
}
}, ct);
// Simulate waiting 3s for the task to complete
Thread.Sleep(3000);
// Can't wait anymore => cancel this task
ts.Cancel();
Console.ReadLine();
}
}
How to use thread.abort()
In case you have to use threads, try this. Otherwise, try cancelAsync like in this link:
https://www.wpf-tutorial.com/misc/cancelling-the-backgroundworker/
// We will set this true to notify the worker threads return.
private bool shouldAbort;
// when hitting submit set:
shouldAbort = false;
void MethodThatDoesWork()
{
//we should stop if required
if (shouldAbort)
{
state.Stop();
}
//code
}
we must be sure that all threads are terminated when the form is closed.
so we add these controls.
private void ItemsCopyer_FormClosing(object sender, FormClosingEventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
private void btnAbort_Click(object sender, EventArgs e)
{
shouldAbort = true;
btnAbort.Enabled = false;
}
C# Aborting a thread: Thread abort is not supported on this platform
Instead of tryng to forcefully abort the thread, you could set a flag to eventually exit the while
loop:
private bool _run = true;
public void refreshRoomList()
{
while (_run)
{
...
}
}
private void roomListBackButtonClick(object sender, RoutedEventArgs e)
{
_run = false;
}
Behaviour of tasks in separate thread on aborting the thread
The i get a strange behaviour: multiple times the
ThreadAbortException
is thrown.
This is normal behaviour for that exception:
When a call is made to the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread. Because the thread can do an unbounded computation in the finally blocks or call Thread.ResetAbort to cancel the abort, there is no guarantee that the thread will ever end. If you want to wait until the aborted thread has ended, you can call the Thread.Join method. Join is a blocking call that does not return until the thread actually stops executing. (Source)
what would be a good solution
You can use Thread.ResetAbort()
to cancel the abortion at that point, but it's almost always better if you don't call Thread.Abort()
. Cancellable Task
s and checks on a volatile "please stop now" boolean are two alternatives. Others may be applicable to your use case. Thread.Abort()
should be reserved only for press-the-big-red-alert-button scenarios, if that.
Related Topics
Printing All Contents of Array in C#
How to Get the Unix Timestamp in C#
How to Set Custom JSONserializersettings for JSON.Net in ASP.NET Web API
Split String Containing Command-Line Parameters into String[] in C#
Automatically Create an Enum Based on Values in a Database Lookup Table
How to Format Datetime Columns in Datagridview
How to Set an SQL Server Connection String
Convert String[] to Int[] in One Line of Code Using Linq
No Connection Could Be Made Because the Target MAChine Actively Refused It 127.0.0.1:3446
Update Row If It Exists Else Insert Logic with Entity Framework
Reading Email Using Pop3 in C#
Conditional Compilation and Framework Targets
How to Delete a Line from a Text File in C#
How to Use Nuget Packages in My Azure Functions
Difference Between 'Throw' and 'Throw New Exception()'
ASP.NET MVC $.Post Call Returning String...Need Help with Format for Jqgrid
Wpf Binding UI Events to Commands in Viewmodel
Create Instance of Generic Type Whose Constructor Requires a Parameter