C#C
C#13mo ago
hugeman

Race condition with Interlocked.Exchange

Hi, I found a weird bug which I can't quite understand...

This is my class: https://github.com/AngryCarrot789/FramePFX/blob/master/FramePFX/Utils/RDA/RateLimitedDispatchAction.cs, it lets me add forced minimum interval between sequential executions (e.g. say you're dragging around a UI control but you only want to update the position text every say 0.1 seconds)

InvokeAsync is called by the user and it choses whether to create a new task or set the current task to a "continue" state. ExecuteCore actually executes the action.

At the very bottom is a generic parameter version, and at one point I hit a break point on the Debug.Assert(false) statement, which to me should be impossible, because ExecuteCore can only be executed if InvokeAsync has been invoked. And even if InvokeAsync gets invoked 10000 times before ExecuteCore, the Interlocked.Exchange should ensure that currentValue is swapped atomically... right? I rarely do multi threaded code so please tell me if i'm being turbo dumb and misusing Interlocked 😄
Was this page helpful?