Shadows234
Shadows234

Reputation: 51

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?

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

Upvotes: 0

Views: 299

Answers (2)

James Gaunt
James Gaunt

Reputation: 14783

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.

So the question is a bit unclear - calling Thread.Abort() is intrinsically safe as it only aborts a thread running in managed code. 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(). 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.

Upvotes: 1

Daniel Slater
Daniel Slater

Reputation: 4143

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.

So aborting here would be fine as long as all disposable things are disposed of properly.

Upvotes: 0

Related Questions