Thread.Sleep(0) doesn't work as described?

前端 未结 5 2005
清酒与你
清酒与你 2021-01-17 19:49

I am currently reading this excellent article on threading and read the following text:

Thread.Sleep(0) relinquishes the thread’s current time slice i

5条回答
  •  轮回少年
    2021-01-17 20:16

    You should (almost) never abort threads. The best practice is to signal them to die (commit suicide).

    This is normally accomplished by setting some boolean variable and the threads should inspect its value to whether continue or not its execution.

    You are setting a string variable named "s". You will incur in race conditions. String is not thread safe. You can wrap the operations that manipulate it in a lock or use a built-in type that is thread-safe.

    Always pay attention, in the documentation, to know if the types you use are thread-safe.

    Because of this you can't rely on your results because your program is not thread-safe. If you run the program several times my guess is that you'll get different outputs.

    Note: When using a boolean to share some state to cancel threads, make sure it is marked as volatile. JIT might optimize the code and never looks at its changed value.

提交回复
热议问题