none
At which senerio race condition occur ? RRS feed

All replies

  • For example, you have two parallel tasks (threads) and a common variable x:

    long x = 0;
    
    var task1 = Task.Run( ( ) => { for( int i = 0; i < 10000000; ++i ) ++x; } );
    var task2 = Task.Run( ( ) => { for( int j = 0; j < 10000000; ++j ) --x; } );
    
    task1.Wait();
    task2.Wait();
    
    Console.WriteLine( x );

     

    The first one increments the x; the second one decrements it. After finishing the tasks, it is expected to obtain 0 in x. However sometimes x has an unexpected result due to “race condition” while performing ‘++x’ and ‘--x’.

    To fix the problem, use Interlocked class or lock.




    • Edited by Viorel_MVP Friday, February 8, 2019 6:03 AM
    • Proposed as answer by Stanly Fan Wednesday, February 13, 2019 2:46 AM
    Friday, February 8, 2019 6:01 AM
  • It's something one has to be aware of in Web solutions on the client side and the browser

    https://medium.com/@slavik57/async-race-conditions-in-javascript-526f6ed80665

    https://www.bennadel.com/blog/2120-exploring-race-conditions-in-javascript-with-setinterval-settimeout-and-ajax.htm

    Friday, February 8, 2019 1:37 PM
  • Hi Anas Babar

    Thank you for posting here.

    According to your description, you want to know race condition about the threading in c#.

    You could read the following link to get it.

    https://www.c-sharpcorner.com/UploadFile/1d42da/race-conditions-in-threading-C-Sharp/

    Best regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, February 11, 2019 3:18 AM
    Moderator
  • Hi

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer, so that it will help other members to find the solution quickly if they face a similar issue.

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.


    Tuesday, February 19, 2019 8:05 AM
    Moderator