Modify a var at the same time

Leon NG 101 Reputation points
2022-10-25T02:20:03.54+00:00

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.

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,762 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 116.8K Reputation points
    2022-10-25T08:56:17.5+00:00

    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).

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. 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.

    253762-99.gif

    ----------------------------------------------------------------------------

    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.