What's wrong with using Thread.Abort()

前端 未结 7 1878
执笔经年
执笔经年 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 22:42

    It's easier to hurt yourself. As others have stated it raises an exception in the code, which can occur at any point. This might be fine if you expect this and have coded in a way that elegantly handles this exception at any point but some people dont:

    Monitor.Enter(obj);
    // some code - if exception is raised here, then the lock isn't released
    Monitor.Exit(obj)
    
    IDisposable someCriticalResource = GetResource();
    // some code - if exception is raised here, then the object isn't disposed
    someCriticalResource.Dispose();
    

    Additionally if you're working with many people on a team unless you have good code reviews you cannot guarantee the quality of the code you'll be working with. Hence it is a good idea to preach the gospal of "no Thread.Abort()" than it is to get people to remember to write code that is robust against exceptions occuring anywhere within that code.

提交回复
热议问题