I converted some c# code to vb.net and the converter.telerik.com turned this:
i--;
into this:
System.Math.Max(System.Threading.Interlocked.Decrement(i), i + 1)
Whats up with all the fancy-ness?
The methods of this class help protect against errors that can occur when the scheduler switches contexts while a thread is updating a variable that can be accessed by other threads, or when two threads are executing concurrently on separate processors.
Interlock. Exchange returns the original value while performing an atomic operation. The whole point is to provide a locking mechanism. So it is actually two operations: read original value and set new value.
Increments a specified variable and stores the result, as an atomic operation.
The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. They also perform operations on variables in an atomic manner. The threads of different processes can use these functions if the variable is in shared memory.
Michał Piaskowski's comment triggered the following explanation:
The semantics of i--
in C# are to return the current value of i
(i.e., the value before the decrement occurs) and then decrement i
by one.
So, we need to convert that to VB. We can not use i -= 1
because this does not return the current value of i
before the decrement. So, we need an operation that will decrement i
but return the value of i
before the decrement, something like:
Function DoPostDecrement(ByRef i As Integer) As Integer
i -= 1
Return i + 1
End Function
But this suggests using the following to avoid having to write a method to perform the above:
System.Math.Max(
someValueThatIsEqualToiMinusOne,
someValueThatIsEqualtoiBeforeTheDecrement
)
But VB.NET won't let you use i -= 1
or i = i - 1
in place of someValueThatIsEqualToiMinusOne
. However, System.Threading.Interlocked.Decrement(i)
is legit and equal to the value of i - 1
. Once you do that, because parameters are evaluated left to right, someValueThatIsEqualtoiBeforeTheDecrement
should be i + 1
(at that point the decrement has been performed to i + 1
is the pre-decrement value.
Note that the above method DoPostDecrement
and the System.Math.Max, System.Threading.Interlocked.Decrement
construct could have different semantics in a multithreaded context.
The Interlocked operation is atomic; in multithreaded contexts you can safely use it without holding a lock, if you're careful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With