dotnet / dotnet/csharpstandard
Document the memory-model related rules
- Dominant language
- C#
- Stars
- 815
- Forks
- 99
- Avg merge
- 1d 14h
- Merged PRs (30d)
- 16
Description
The current standard seems to say relatively little on the memory model issues. The all information I could find is only the [§7.10](https://github.com/dotnet/csharpstandard/blob/draft-v7/standard/basic-concepts.md#710-execution-order).
There is an ongoing work on documenting the memory model in the runtime repository (https://github.com/dotnet/runtime/issues/63474 and in particular [Draft of CLR Memory model](https://github.com/VSadov/runtime/blob/memModel/docs/design/coreclr/botr/memory-model.md)), but it seems to discuss the things in terms of memory locations and loads/stores, whereas the developers usually have to reason in terms of variables/assignments/initialization etc. (and there are no clear guarantees on whether a variable corresponds to a memory location or not, an assignment corresponds to a store, etc., especially for the optimizing compiler and non-trivial code generation cases like lambda captures or iterators/async functions). This means that the mentioned document is most probably not enough for the language users.
The language's memory model requirements need to be documented as a part of C# standard.
---
A simple example would be creating an immutable object instance and using it from other threads. Though being de facto allowed/safe from the CLR's point of view, the correctness of this pattern doesn't follow from §7.10.
Another example would be subscribing to an event in one thread and dispatching the event in another thread through `Event?.Invoke(...)` (which is guaranteed thread-safe by the documentation but not mentioned in the Standard).
Another example would be [using the class fields in its Finalizer](https://docs.microsoft.com/en-us/dotnet/api/system.idisposable?view=net-6.0): the code in the documentation doesn't do any synchronization, so the correctness of this code should be somehow deducible from the standard.
Contributor guide
Assessment
This issue has not been assessed yet.