synchronization through EventWaitHandle not working as expected

273 views Asked by At

so basically this is the code I've been testing

static void Main(string[] args)
{
    var result = 0;

    EventWaitHandle calcDone = new EventWaitHandle(false, EventResetMode.ManualReset);

    ThreadPool.QueueUserWorkItem((x) => { result += GetNumer(); calcDone.Set(); });

    var result2 = 15;

    calcDone.WaitOne();

    result += result2;

    Console.WriteLine(result2);
}

static int GetNumer()
{
    Thread.Sleep(2000);
    return 2000;
}

so basically you would expect 2015 to be written in console windows but no, just 15 is output. WaitOne is working OK because until the GetNumber returns and increments the result the execution is stopped but afterwards I don't know what happens. If you just debug the code and ho step by step everything is OK but if you just run the code it outputs 15. Am I doing something wrong here ? please don't ask why am I using thread pools and not tasks. it's just for testing purposes.

1

There are 1 answers

1
Soonts On BEST ANSWER

The only line of code that changes your "result2" variable is var result2 = 15;. After that, result2 remains 15 while you're incrementing your result variable.

P.S. Excellent illustration why you shouldn't name your variables like "result2" or "variable4".