1

Is it threadsafe to computer a value before using it inside a Task using a lambda expression. Inside the Task 'param' is used from a different thread. Is it garanteed that the closure variable 'param' is visible on the Tasks thread when the Task starts immediately after it was computed? Or is it necessary to lock the access to 'param'? After param is computed, it shall be considered to be readonly from this point.

Without lock:

int param = a + b; // param shall be considered immutable after it was calculated
Task.Run(() => MethodWithParameter(param));

With Lock:

int param;
lock(obj) param = a + b; // param shall be considered immutable after it was calculated
Task.Run(() => {
    int p2;
    lock(obj) p2 = param
    MethodWithParameter(p2)); 
}
bebo
  • 819
  • 1
  • 9
  • 26

1 Answers1

-1

Yes, TPL includes the appropriate memory barriers when tasks are queued and at the beginning/end of task execution, so that values are appropriately made visible to other threads.

Sources:

  1. Are you there, asynchronously written value?
  2. Memory barrier generators
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104