I have code like this (simplified):
long counter = 0L;
var t = Task.Run(async () =>
{
Interlocked.Increment(ref counter); // Resharper: "Access to modified closure"
await Task.Delay(500); // some work
});
// ...
t.Wait();
// ...
Interlocked.Decrement(ref counter);
counter
variable is used to control total number of something in progress.
In the lambda (as well as outside it) the variable is only referenced with ref
. How does the compiler process such captures? Is it guarantied that all delegates (if many) will get the same reference to counter
, not to "individual" copied variables? I tested it and it works as expected, but I want to be sure.
Is it safe to use explicit
ref counter
for interlocked change and read?Why does Resharper gives this wacky suggestion to wrap the variable in one-element array? Like this:
long[] counter = {0L}
,Interlocked.Increment(ref counter[0])
. Can you provide a use-case when it helps or fixes something?
P.S. The question was induced by another my question.
NOTE: I am aware what closure is and how it works in common cases. Before marking the question as duplicate read concrete questions 1 and 2. I did not find answers to these questions in multiple "loop-closure" questions in Internet and SO.