Start and stop(forced) a threaded job

后端 未结 3 991
栀梦
栀梦 2020-12-11 08:52

I want to know a proper way to start and stop a threaded job forced and unforced. Is this the proper way to stop a Thread?

    public class ProcessDataJob :          


        
3条回答
  •  孤街浪徒
    2020-12-11 09:25

    There is no proper way to forcibly kill a thread.

    There are several ways to do it, but none of them are proper.

    Forcibly killing a thread is what you should do only if you need to terminate the program, or unload the appdomain containing the thread, and don´t care about any data structures left dangling in a corrupted/bad/locked state, because they will be gone in a short while as well.

    There´s plenty of advice on the internet about how bad/evil Thread.Abort is, so don´t do it.

    Instead, write proper cooperative threading. The thread(s) should themselves check a flag (event, volatile bool field, etc.) and then voluntairly exit when nicely asked to do so.

    That is the proper way.

提交回复
热议问题