Suppose the following code (note that this is only sample code):
public async void UnsafeMethod()
{
int unsafeValue = 0;
Task.Run(() => unsafeValue = 42 );
await Task.Delay(10);
Assert.AreEqual(42, unsafeValue);
}
(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 );
await Task.Delay(10);
Assert.AreEqual(42, safeValue);
}
(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);
await Task.Delay(10);
Assert.AreEqual(42, safeValue);
}
(The task runs immediately.)
. https://msdn.microsoft.com/en-us/library/system.threading.volatile(v=vs.110).aspx
:
, , , .
. :
. , , , : .
, , , .
: , ( )?