What's wrong with using Thread.Abort()

前端 未结 7 1871
执笔经年
执笔经年 2020-11-21 22:30

So I know that you shouldn\'t use

Thread.Abort()

But I\'ve never been given a good explanation. Is there a performance penalty or some hid

7条回答
  •  鱼传尺愫
    2020-11-21 22:38

    In addition to all of the other good answers here, let me add that there is no guarantee whatsoever that a call to Thread.Abort will actually abort the thread in question, ever. It is possible (though not particularly easy) to "harden" a thread against being aborted. If, for example, you are aborting a thread because you believe it to be running hostile code then the hostile code could be resisting its own destruction.

    If you have a long-running operation involving code that you do not own that must be taken down cleanly, the correct way to do this is to put that code in its own process, not its own thread. (And preferably in a highly security-restricted appdomain in that process.) You can then cleanly kill the process.

    In short, Thread.Abort is at best indicative of bad design, possibly unreliable, and extremely dangerous. It should be avoided at all costs; the only time you should ever even consider aborting a thread is in some sort of "emergency shutdown" code where you are attempting to tear down an appdomain as cleanly as possible.

提交回复
热议问题