How are ref variables being captured in closure? [duplicate]

江枫思渺然 提交于 2020-01-03 15:32:22

问题


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.

  1. Is it safe to use explicit ref counter for interlocked change and read?

  2. 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.

来源:https://stackoverflow.com/questions/48194818/how-are-ref-variables-being-captured-in-closure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!