Repository navigation
Description
So Thread.Abort / Thread.Suspend are not just deprecated, they're removed outright from .NET Core, which I think is unnecessary.
.NET Core's nature is to power performance-critical online services, and for services, being "alive" is everything. A lot of efforts can be spent on making the service resilient against unexpected events.
.NET Core is also a very good embedding engine to power a plug-in like system (the service stays native, and extension code runs in .NET Core embedded in the host native service), it's not always realistic to expect that all code running on top of .NET Core to cooperatively check for cancellation tokens, nor would that completely eliminate the risk of "3rd party" extension code misbehaving.
Therefore, as a last resort, it's often required to do whatever is in the power of the service to stay live and being able to serve requests, even at the risk of having partially corrupted state and/or partially inconsistent state, for two reasons:
- for a well-designed plug-in system, it can be designed so that any state the plug-in code can access & manipulate is per-request, so corruption to the state doesn't have global effects.
- not every service is so sensitive to state corruption like database services, often times, arguments can be made that partially correct results can be better than no results.
That is, even if Thread.Abort can lead to inconsistent or corrupted state, it shouldn't be the reason to remove it all together from our toolbox.
We should trust service engineers' ability to weigh the risk against the benefit to make decision on their particular case, instead of worrying that they will shoot their foot somehow.
I think the extreme insistence on a "no corrupted state" program (hence the mindset "just crash if state is corrupted") doesn't apply well to today's service oriented world.
Bottom line is, without these two APIs, I have no way to stop suspected infinitely looping threads from eating up my cores and bring down my service's capacity, which is a big deal for services.
Activity
GSPP commentedon Oct 31, 2018
I think the case you make is very reasonable. It is also my opinion that the risk trade-off for aborts can be worth it. ASP.NET for example implements request timeouts with
Thread.Abort. But this approach can absolutely destroy the entire app domain (for example by crashing a static constructor). I usually disable the request timeout entirely therefore.I personally have never seen a good case for
Thread.Abortbut I'm sure it exists. You seem to be in a place where you sometimes need to abort 3rd party code as a mitigation of last resort. It certainly is a radical stance to removeThread.Abortfrom the platform and prevent these good use cases.It would be incorrect to say that the corruption risk of
Thread.Abortis never worth it. Real world applications sometimes require nasty trade-offs.I'm personally very happy to see the scourge that is
Thread.Abortto be purged from the platform. So much evil has been committed using it. It's a net benefit to prevent it from being used even considering that valid use cases are prevented as well.pongba commentedon Oct 31, 2018
@GSPP thanks for the detailed and considerate response. I have actually encoutered a case where I would like to be able to abort a thread - the thread executes some extension code not owned by the service owner, if it end up busy looping, it will eat up my cores, bring down service capacity, or even kill the service.
To restart the whole service would be a too aggresive move and is subject to false alarm / overreaction, and probably won't help anyways, since new request can still make the situation re-occur.
Only viable damage control is to stop further execution of such misbehaving code - but what's already damaged can not be reversed, i.e. we can stop more cores from being further eaten up, but what's already eaten up (we of course set a maximum limit N) cannot be brought back unless we can suspend or abort the bad thread.
P.S.
[1] I don't think the static constructor situation is always a big concern - sure it can bring down the whole appdomain, but first of all, this is only a disaster for managed service, since the whole service may relie on the appdomain to function, but for hybrid services (becoming more & more common nowadays), the dying of an appdomain is simply one fault that can be tolerated or even partially recovered from (say recreate the appdomain, or recreate the .NET Core CLR), second of all, isn't there ways to make sure a certain area of code (e.g. extension code) never uses static constructors through roslyn code analysis?
[2] While I was doing my research on the whole Thread.Abort/Thread.Suspend situation, I found that there's a huge discrepancy in what experts out there are advising and what the industry is demanding, i.e. almost all experts in the field strongly discourage against / frown upon / outright forbid the use of Thread.Abort/Suspend, which I totally agree is very valid recommendation and for very good reasons, I admit I probably would've done the same if I were to give general suggestions. However, I also see that there're a whole lot of requests from engineers who're crying out loud for a way to abort misbehaving code, and no, cooperative cancellation is often not an option, despite being repeatedly suggested on. The situations they face are often similar or identical to what I have mentioned above. And I would only imagine with the ever more pervasiveness of cloud services and hybrid architecture (using .NET Core as intra-process containers akin to v8/Node.js), this demand is only going to be more loud. And the reason we don't see a lot of yelling is not necessarily due to it not being important, but the human nature to work with what they've been given, i.e. to workaround or tolerate it with what they have in their toolbox, which are not ideal.
benaadams commentedon Oct 31, 2018
Core CLR doesn't have appdomains; it will crash the process
pongba commentedon Oct 31, 2018
@benaadams I know. But not if CoreCLR is hosted by a native process.
benaadams commentedon Oct 31, 2018
Could use multi-process and terminate the process instead? Porting to .NET Core - AppDomains
pongba commentedon Oct 31, 2018
I completely agree that Thread.Abort should not be used as a timeout mechanism, because timeout is a very frequent event, and repeatedly Thread.Aborting is not a pretty scene to imagine.
In my mind, Thread.Abort is never supposed to be used for timeout.
It's instead used for "this-thread-is-definitely-doing-evil-stuff-like-infinitely-looping-or-blocking", which is a whole different category than normal everyday timeout. Admittedly it's theoretically impossible to determine if a thread is indeed in this kind of state, but in practice it's often possible to do so through domain knowledge particular to one's particular service and application; a very simple way that often works is to have a very relaxed timer that should the timer fires, then definitely things are going south. And this timer is of course conceptually different from the ordinary timeout timer (usually it's much longer)
pongba commentedon Oct 31, 2018
Yes. That can work. But that kind of destroys the whole essence of .NET Core's main battleground - extreme performance. Not to mention that it's often a huge a mount of dev work to make the process level isolation work nicely if the communication protocol between the processes are not "trivial" such as a blob of data tossed over (shared memory of course) the boarder and then response blob of data received once the other process has done its job.
GSPP commentedon Nov 1, 2018
Even
System.Stringhas a static constructor. All kinds of types initialize caches using them. That said all of these would typically occur in the first few moments of an application's execution. It does not seem to be a huge problem in practice but it bears the potential of permanently bring down the appdomain.mnmr commentedon Nov 1, 2018
The documentation for Thread.About is very specific about what the method can and cannot do: "It might terminate the thread". That's not a great API to support in .NET Core.
Unless Windows starts offering something with better guarantees I fully support the decision to NOT have these mechanisms in .NET Core. There is also the concern that whatever mechanism .NET Core introduces, it should work across operating systems.
You can start multiple processes and use that to provide reliability. It's not as convenient as handling it internally in a single process, but you can do it without using API's that are documented "to maybe work".
Suchiman commentedon Nov 1, 2018
@mnmr this has little to do with windows offering something or cross platform. Calling
Abortthrows an asynchronous exception (async because it is not caused by something that thread is doing itself) into the target thread. That can only happen in managed code (since unmanaged code doesn't support .NET exceptions) when not in finally blocks (because those have well defined behaviors of will always execute if possible at all) and will only abort if the target thread doesn't cancel the abort by catching it and callingResetAbort. Those are well defined behaviors. Similiar one could argue that starting another process is not a great API to support in .NET Core either because it "only maybe works" since you can run out of system resources necessary to start a new process. And callingCancellationTokenSource.Cancel()has even less chances of actually cancelling work as that relies on the code actually checking theCancellationTokenwhich it will do irregular and it might be stuck somewhere where it doesn't check.pongba commentedon Nov 1, 2018
@mnmr Multi-process is often a costly option that goes against the the latency requirement.
And whether an API has guaranteed success or not shouldn't be the reason for banning it outright. As @Suchiman said, they're orthogonal matters. We have a whole lot of APIs that "may or may not" succeed.
I would argue that it's a philosophical question eventually, i.e. whether to trust engineers' ability to make judgments on their own, or babysit them by taking away the sharp objects from the playpen.
In the past where .NET's major battleground was not extreme performance-sensative areas, I would say the babysitting approach was fine, but, nowadays we see .NET Core extending deep into so many extremely performant areas where not only it's required to have riskier APIs, but also where service engineers working there are capable of making risk-aware choices for themselves.
The bottom line is: I don't really see the downside of including the API, since with the current state of C# development environment, we can state very clearly the danger (when and how, and the alternatives, if they apply) in "in-code documentations" such as [Obsolete] tag, and enforce them through warnings, code analysis suggestions, and etc. With these on-the-spot educational tips while the code is being written, I really don't see the over worrying sentiment behind this API, after all they have been included in Windows API since like forever.
Suchiman commentedon Nov 1, 2018
This is something particular observed well in .NET Core, prior examples include removing
StackTracebecause some developers abused it in an ORM to check for transaction nesting which is really bad but no reason to punish everyone.pongba commentedon Nov 1, 2018
@Suchiman yup, and I worry about the philosophy behind these kind of decision makings, particularly because this is .NET Core, this is in and of itself the sharp sword we're handing over to service engineers who would go to great length to squeeze out the last drop of performance gain, and now we're worried about them cutting themselves because we didn't remove some rough edges on the sword's handle. This is paradoxical. Why then don't we ban "unsafe" all together?
And trust me I want .NET Core to be successful as much as anyone. I want to migrate my project over to .NET Core, but without Thread.Abort / Thread.Suspend I couldn't achieve the same level of robustness / resilience that I can through .NET Framework 4.7, and I don't think downgrading services' level of robustness is a very good option (process isolation is not an option either). The case is particularly bad because I couldn't even fashion my own alternative through P/Invoke to Win32 TerminateThread, since they're totally different animals.
And I even want a Span that directly holds pointers to native heap (to reduce interop cost to essentially 0; as of now to my understanding of Span if I need to expose a native std::string's guts to managed code, 1 copy of memory is still needed.)
svick commentedon Nov 1, 2018
@pongba
Experienced developers who care a lot about performance are not the only target audience of .Net Core. It's also meant to be used by beginners, and everyone in between the two extremes, so I don't see the paradox. Performance is important, but it's not the only important thing.
And the difference between
unsafeandThread.Abortis thatunsafeis hard to use safely, while it's generally considered impossible to useThread.Abortsafely.Span<T>has a constructor that takes a pointer an length, so I don't see why accessingstd::string::datathoughSpan<byte>would require a copy. Though I think that discussion is off-topic on this issue.pongba commentedon Nov 1, 2018
@svick Thanks a lot, it appears that my readings were off. This is great to know. I was (incorrectly) under the assumption that Span has to hold interior pointers to GC managed objects.
21 remaining items
jkotas commentedon Aug 24, 2020
We still have the "good enough" thread abort functionality available for debuggers via debugging APIs. If the other debugger-like environments cannot act as real debuggers, I would not be opposed to exploring ways how to make the thread abort available to them.
dsyme commentedon Aug 24, 2020
Ah interesting. cc @eiriktsarpalis @KevinRansom
Could you link me any docs on this? Thanks
jkotas commentedon Aug 24, 2020
https://docs.microsoft.com/en-us/dotnet/framework/unmanaged-api/debugging/icordebugeval-abort-method
dsyme commentedon Aug 24, 2020
@jkotas Just to check, can processes open debug connections to themselves, or do they need an external process to be the debug process?
Also cc @jonsequitur since it's related to Interrupt in .NET Interactive and Jupyter notebook.
jkotas commentedon Aug 24, 2020
Debugger needs to be external process.
dsyme commentedon Aug 24, 2020
Ah I see, so all evaluation must be submitted via debug API. Hmmm... Well, it's something to think about.... though very different to what we are doing today for F# Interactive etc.
It wouldn't be totally impossible to rearchitect the F# REPL to use a supervised process but it would be a large amount of work. And that work would likely be needed again for .NET Interactive and C# REPL.
If it were possible to put on the agenda a
System.Runtime.Helpers.UnsafeThreadAbortOnlyForUseByInteractiveExecutionEnvironmentsActingAsTheirOwnSupervisor()that would be grand....dsyme commentedon Aug 24, 2020
Could we reopen this issue to keep this specific possibility tracked?
jkotas commentedon Aug 24, 2020
The case that started this issue was production scenarios. The case for debugger-like scenarios should be a new issue.
dsyme commentedon Aug 24, 2020
Ah ok. I'll start an issue
dsyme commentedon Aug 24, 2020
Issue is here: #41291
akovac35 commentedon Sep 14, 2020
I would like to comment on this issue as a client: We (keep it confidential for now) have started using .NET Core for our new software projects. The platform is great, in general most can be achieved rather efficiently. But quirks such as this one are quite scary - for example, right now I am working on an application which requires an operation to run in a new thread (pretty much isolated operation), but after some time the operation should be aborted. Because the operation consists of invoking WCF, REST and HTTP services, many of which are generated, it is practically impossible to apply a timeout to all of them (30 distinct clients), especially because all possible timeouts are not accessible (open request, read request, write, etc.). So I have tried to use Abort, which is surprisingly deprecated, and the only remaining option is to simply run the operation in a new task or thread and let the thing timeout via default settings, hopefully! implemented by enterprise systems aware developers. This would normally not be OK, because the operation would modify data in connected systems, but in this health check application this is possible.
But for our other applications this will definitively be a major problem. What options are available to us for resolving this problem (paid support, service ticket, manager contact, ...)?
<See below for additional information, the issue may not be so critical after all.>
jkotas commentedon Sep 14, 2020
Thread.Abortfor production scenarios is not going to come back to .NET Core. I am sorry.The best solution is to make the services that you are using to be exposed via cancellable async operations.
akovac35 commentedon Sep 14, 2020
Thanks for the suggestion.
I must add that the operation in a new thread does not invoke all 30 of the clients, but only one client per thread is invoked in series or in parallel, as configured (that was the intention). So typically this would be a short operation, but if the service is slow, the thread my take longer than the health check threshold. Because I am simply invoking a service client, it is not possible to poll for cancellation token. But it does seem to be possible to configure timeouts for most of our requirements, perhaps the issue will not be so problematic. Below is a short listing in case anyone hits this page searching for timeouts, .NET Core and service clients:
It is possible to set binding timeouts the same way as in .NET Framework for WCF .NET Core clients:
https://docs.microsoft.com/en-us/dotnet/framework/wcf/feature-details/configuring-timeout-values-on-a-binding
Then there are REST clients which typically use HttpClient. It has a Timeout property which may be useful as well: https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=netcore-3.1
The above represents most of the service clients and the remaining ones will just have to be dealt with one at a time. If anyone hits the same situation, don't forget to tell the manager that patience is a virtue ;)
jinek commentedon Nov 25, 2020
It is about almost any other code.
Many developers don't understand their program can be stopped at any moment.