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
- . . , , . . , , "" - . , .
, . , - :
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 , .
.
, . , ! .
, . , , / , Interlocked .
.Net , int read/write . , 32-, 64- ! / .
, , Interlocked.Increment.
int? , int, 32 , .
, / = > .
Btw, , , Interlocked .
, . , . , , , ..
, Interlocked .
, / , , / , .Add , interlocked.CompareExchange , . , !
Source: https://habr.com/ru/post/1626904/More articles:Python Regex Capture text between matches - regexElasticsearch - derivative of deep metric - aggregationHow to get name of parameter value when check returns false in laravel 5 - javascriptApplying rainbow text to all text in a class - javascriptAndroid search viewing course does not appear as one toolbar color - androidHow to sum elements in Node recursively in Java? - javaQPrinter cannot correctly set up an HTML page to render an image in a PDF document - c ++MS Edge Cross-captioning not working - microsoft-edgeBeyond TDD: Should I check for failed acceptance tests? - unit-testingUse git rebase because it is easier to revert changes? - gitAll Articles