2

In one of our old services I found such piece of code (comments are original):

long[] tasksCounter = {0};  //boxing for long counters
long[] errorsCounter = {0}; //boxing for long counters

Further in the code these "arrays" are used with Interlocked class: Interlocked.Increment(ref errorsCounter[0]), Interlocked.Read(ref errorsCounter[0]) etc).

I wonder why did not the author use basicaly long tasksCounter, errorsCounter?

Probably this approach has benefits I don't know about?

It's probably worth mentioning that the variables are used in async lambda. When I change it to basic long Resharper plugin warns me with "Access to modified closure" and suggests to wrap it in array. I found couple of questions about it:

Access to Modified Closure

ReSharper Warning - Access to Modified Closure

Robert Harvey
  • 178,213
  • 47
  • 333
  • 501
greatvovan
  • 2,439
  • 23
  • 43
  • 1
    Did the original author come from the Java world, which doesn't have `ref` arguments? – DodgyCodeException Jan 10 '18 at 17:48
  • @DodgyCodeException I don't know, he does not work here anymore... – greatvovan Jan 10 '18 at 17:50
  • 3
    I know a developer, who is otherwise quite talented, who likes using arrays to hold single items because *inaudible muttering*. I think its just how they learned it in school and no one corrected them, so they've done it that way ever since and because it works, why stop? –  Jan 10 '18 at 17:57
  • So does your update answer your own question? – Robert Harvey Jan 10 '18 at 17:59
  • 1
    Guys check the update. Probably this was Resharper's suggestion. – greatvovan Jan 10 '18 at 18:00
  • @RobertHarvey Probably. I am reading these answers and trying to understand whether this suggestion is important in my case. – greatvovan Jan 10 '18 at 18:01
  • But why wrap in array and not just create a copy in temp variable? I don't remember resharper ever suggested me to wrap into array in case of captured closure. – Evk Jan 10 '18 at 19:32
  • @Evk Check another my question. With that code example one of the latest Resharper versions does suggest me this: https://stackoverflow.com/questions/48194818/how-are-ref-variables-being-captured-in-closure – greatvovan Jan 10 '18 at 19:36

0 Answers0