Are class member enumeration streams safe?

Take as an example

public class MyClass
{
      private MyEnum _sharedEnumVal { get; set; }
}

If the methods in MyClass were executed in different threads and read / updated _sharedEnumVal, am I right in saying that to save a thread safety variable, like other primitives, or special enumerations, do you need the right to block or another mechanism?

thanks

+4
source share
2 answers

- . . , , . . , , "" - . , .

, . , - :

 public void DoSomething()
 {
    if (_sharedEnumVal == MyEnum.First) {
       DoPrettyThings();
    } else {
       DoUglyThings();
    }
 }

 public void UpdateValue(MyEnum newValue)
 {
     _sharedEnumVal = newValue;
 }

:

 static MyClass threadSafeClass = new MyClass();

 void ThreadOne()
 {
    while (true) 
    {
        threadSafeClass.UpdateValue(MyEnum.Second);
        DoSomething();
    }
 }

 void ThreadTwo()
 {
    while (true)
    {
       threadSafeClass.UpdateValue(MyEnum.First);
       DoSomething();
    }
 }

, , "" , DoSomething, , . . ThreadTwo , ThreadOne , .

.

+3

, . , ! .

, . , , / , Interlocked .

.Net , int read/write . , 32-, 64- ! / .

, , Interlocked.Increment.

int? , int, 32 , .

, / = > .

Btw, , , Interlocked .

, . , . , , , ..

, Interlocked .

, / , , / , .Add , interlocked.CompareExchange , . , !

0

Source: https://habr.com/ru/post/1626904/


All Articles