There is a nullable variable, which requires access from different threads. For example, int? . What method of synchronization of such a variable should be used in C #? The most straightforward is to wrap it all in a lock . There was an assumption that volatile will cope with it, but it does not know how to c nullable .

What if you need to copy this value locally, write a function (lambda) whose body is wrapped in a lock ? Copying primarily in order to reduce the blocking time between threads.

  • one
    For synchronization you need to use lock . Other methods are allowed to use if you need extreme optimization, and you understand very well what you are doing. (In particular, if you do not have dependent variables.) - VladD
  • I usually rewrite algorithms so that they do not have a shared state at all. Thus, the need for synchronization disappears by itself. - VladD
  • Why lambda? int? local; lock (mutex) local = shared; // используем local int? local; lock (mutex) local = shared; // используем local - VladD
  • Although of course it depends on the exact meaning of what you need. - VladD
  • @VladD I wanted to combine with initialization, that's why I thought about (lamba) functions. It is difficult not to use a shared state when you need to transfer this state. - αλεχολυτ

0