简体   繁体   English

C#线程中止安全

[英]C# Thread Abort safety

Using 使用

SqlDataSourceEnumerator.Instance.GetDataSources();

Within a running thread, is it safe to call thread.Abort() while that is still running to kill the process? 在正在运行的线程中,在仍在运行以终止进程的情况下调用thread.Abort()是否安全?

Note: That's a thread within a background worker. 注意:这是后台工作程序中的一个线程。 I need to be able to cancel the background worker, but can't if that one line is blocking 我需要取消后台工作人员,但是如果那一行阻塞了就不能取消

If the thread is blocking in unmanaged code Thread.Abort() won't do anything until the thread returns to managed code anyway, which you seem to acknowledge with your Note. 如果线程在非托管代码中阻塞,则Thread.Abort()不会执行任何操作,直到该线程无论如何都返回到托管代码为止,您似乎已经注意到了。

So the question is a bit unclear - calling Thread.Abort() is intrinsically safe as it only aborts a thread running in managed code. 因此,问题有点不清楚-调用Thread.Abort()本质上是安全的,因为它仅中止在托管代码中运行的线程。 So when you say "is it safe" what dangers are you worried about? 因此,当您说“安全”时,您担心的是什么危险?

If you need to be able to abort unmanaged calls one way is to spin them off in a separate process so you can use Process.Kill(). 如果您需要中止非托管呼叫,一种方法是在一个单独的进程中将其剥离,以便可以使用Process.Kill()。 Then you're passing off the job of dealing with the clean-up to the operating system. 然后,您将完成对操作系统的清理工作。 On the downside of course you have to do some boilerplate code to send data to/from the process. 当然,不利的一面是您必须执行一些样板代码以将数据发送到流程或从流程发送数据。

I don't think anyone can guarantee this completely as there are many unmanaged libraries that get called through a database connection. 我认为没有人能完全保证这一点,因为有许多通过数据库连接调用的非托管库。

The best practice for a user of the service is to dispose of all disposable objects related to your sql connection, and you should expect to be safe. 服务用户的最佳实践是处置与sql连接相关的所有一次性对象,并且您应该确保安全。

So aborting here would be fine as long as all disposable things are disposed of properly. 因此,只要妥善处理所有一次性物品,在这里中止就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM