I think that the behaviour is undefined because the "++" and "--" operators are not atomic (https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/variables#96-atomicity-of-variable-references). You should use Interlocked.Increment and Interlocked.Decrement. Then the variable will contain the result of the most recent thread (that waited for completion of operation performed by other threads).
Modify a var at the same time
Hi there,
I create a timer and worker. What will be the result if they try to modify a var at the same time?
e.g.
var = 10
timer { var--; }
worker { var++; }
Thank you.
1 additional answer
Sort by: Most helpful
-
Hui Liu-MSFT 48,511 Reputation points Microsoft Vendor
2022-10-25T05:54:00.217+00:00 Hi,@Leon NG . Welcome Microsoft Q&A.
For the problem of modifying var at the same time, here is an example of Timer and Worker. And you can see the resulting graph at the end.Xaml:
<StackPanel> <TextBox Text="{Binding Num,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" Width="100" Height="50" Background="AliceBlue"/> <ListBox x:Name="lb1" Width="100" Height="100"/> <Button x:Name="btn" Content="timer" Click="btn_Click" Height="50" Width="100" /> <Button x:Name="btn1" Content="worker" Click="btn1_Click" Height="50" Width="100" /> </StackPanel>
Codebehind:
253680-timerand-worker.txt
The result:
Set the number of worker job(loop) to 5 for testing, if more than 5 times, only the timer is working.----------------------------------------------------------------------------
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.