Multithreading/Concurrency/Parallel – gurantees about value read by a thread?

Jiří Čepelka 96 Reputation points
2020-12-02T17:30:02.107+00:00

I wonder if there is a guarantee in the .NET about a value read by some thread from a field write by another thread.

This question is not about syncing the threads via sync primitives. I do not care about race conditions or a thread-safety. Also I do not asking a field volatility since for me it is not important to have not writes in original order.

Let check simple example

private bool m_isBusy;
public bool IsBusy
{
    get => m_isBusy;
    set 
    {
      m_isBusy = value;
      NotifyPropertyChanged();
    }

}

public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
    InvokeOnUIThread
    (
        () => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName))
    );
}

So there is a view model (constructed by the UI thread or by another thread for instance by an IoC container). Looking into NotifyPropertyChanged it is obvious that PropertyChangedEventHandler will run on the UI thread so it is sure it will be the UI thread that will check for a new value.

So what guarantees in this particular scenario where any thread can set IsBusy that the UI thread will find there the value that was set and not the value it has there already❔

There is good question regard this on StackOverflow (Can a C# thread really cache a value and ignore changes to that value on other threads?) but it seems little outdated.

I am almost 100 % sure that I am aware that any thread will get an actual value (not some CPU cached value, or other cached one (?)) but I cannot find the precept which tells this is guaranteed.

Is there some official statements about such guarantees?

.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,119 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiří Čepelka 96 Reputation points
    2020-12-03T15:59:19.327+00:00

    Almost. I want to know (guarantee) whether some thread reading consequently after another thread finished writing a value to a field (can be forced for instance by locking access) will get the value written by another thread.

    I was searching and reading somehow since I asked so I know now there is no such guarantee.

    There are 2 options it seems:

    1. Transfer the responsibility for writing to the thread that is interested in reading.
    2. Switch to the volatile memory operations (there is lot of reference on this).

    Thank you for reference I am going to review it.

    0 comments No comments

0 additional answers

Sort by: Most helpful