Multithreading and booleans

前端 未结 2 517
你的背包
你的背包 2020-12-11 04:38

I have a class that contains a boolean field like this one:

public class MyClass
{
    private bool boolVal;
    public bool BoolVal
    {
        get { retu         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-11 05:35

    volatile alone is not enough and serves for a different purpose, lock should be fine, but in the end it depends if anyone is going to set boolVal in MyClass iself, who knows, you may have a worker thread spinning in there. It also depends and how you are using boolVal internally. You may also need protection elsewhere. If you ask me, if you are not DEAD SURE you are going to use MyClass in more than one thread, then it's not worth even thinking about it.

    P.S. you may also want to read this section

提交回复
热议问题