Issue
the decimal type takes 128 bits, so it is not naturally an atomic write.
I tried:
Interlocked.Exchange(ref myField, some new value)
but then I saw that decimal is not part of the supported types with Interlocked.Exchange.
I was thinking that doing a lock may be a little bit heavy for this write. Are there any other options?
Solution
As you said, Interlocked.Exchange
can only work with 32bit or 64bit values, so it does not support decimal
. Aside from using locks, one suggestion from a related C# StackOverflow post is to wrap the value in an object and then use Interlocked.Exchange
to swap the object references. In F#, this would look like this:
type Boxed<'T when 'T : struct>(v:'T) =
member x.Value = v
let mutable d1 = Boxed(1M)
let d2 = Boxed(2M)
Interlocked.Exchange(&d1, d2)
The question is whether the overhead of an additional instance is greater than the overhead of using lock
- I think this will depend on your specific case. If you have just a few decimals that you're working with, the extra objects may not be such a big deal, but you'll probably need to run some tests to find out.
Answered By - Tomas Petricek Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.