Using volatile.Write () instead of volatile in C #

Suppose the following code (note that this is only sample code):

public async void UnsafeMethod()
{
  int unsafeValue = 0;

  Task.Run(() => unsafeValue = 42 ); // set unsafeValue to some value
  await Task.Delay(10);              // wait for some time

  Assert.AreEqual(42, unsafeValue);  // check if unsafeValue has the new value
}

(Suppose the CPU is idle and immediately performs a task.)

Since the task will be executed in a new thread, the new value unsaveValuemay not be displayed for other threads due to possible caching problems. If I want to make the change visible, I will need to use volatileand make the local variable field:

private volatile int safeValue = 0;

public async void SafeMethod()
{
  Task.Run(() => safeValue = 42 ); // set safeValue to some value
  await Task.Delay(10);            // wait for some time

  Assert.AreEqual(42, safeValue);  // check if safeValue has the new value
}

(Assume once again that the task runs immediately.)

Now my question is: if the following will be executed while saving a local variable (I know that the compiler does this field anyway ...):

public async void AnotherMethod()
{
  int safeValue = 0;

  Task.Run(() => Volatile.Write(ref safeValue, 42); // set safeValue to some value
  await Task.Delay(10);                             // wait for some time

  Assert.AreEqual(42, safeValue);                   // check if safeValue has the new value
}

(The task runs immediately.)

. https://msdn.microsoft.com/en-us/library/system.threading.volatile(v=vs.110).aspx

:

, , , .

. :

. , , , : .

, , , .

: , ( )?

+4
1

Matteo Umili , , Volatile.Read, . , 2 .

Volatile.Write - , Volatile.Read .

-1

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


All Articles