Modify a var at the same time

Leon NG 101 Reputation points

Hi there,
I create a timer and worker. What will be the result if they try to modify a var at the same time?
var = 10
timer { var--; }
worker { var++; }

Thank you.

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,564 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 106.5K Reputation points

    I think that the behaviour is undefined because the "++" and "--" operators are not atomic ( 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).

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Hui Liu-MSFT 23,606 Reputation points Microsoft Vendor

    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.


            <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" />  


    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.

    0 comments No comments