I am trying to use the ManualResetEventSlim
class to communicate between a few parallel Tasks.
Here is a simplified version of the code:
class Program
{
private static void Main(string[] args)
{
Stopwatch stopwatch = Stopwatch.StartNew();
ManualResetEventSlim eventSlim = new ManualResetEventSlim(false);
Task.Run(() =>
{
Task.Run(() =>
{
Thread.Sleep(1000);
eventSlim.Set();
});
eventSlim.Wait();
Console.WriteLine($"Hello from the Task! {stopwatch.Elapsed}");
});
eventSlim.Wait();
Console.WriteLine($"Hello from the Main thread! {stopwatch.Elapsed}");
stopwatch.Stop();
Console.ReadLine();
}
}
Most of the times the code runs fine and outputs:
Hello from main thread! 00:00:01.1017591
Hello from task! 00:00:01.1017630
However once in every five or six times I run the code I only get this output:
Hello from main thread! 00:00:01.1017591
And the code after the Wait
inside the Task never gets called.
I'm using .NET Core 2.0.2
on Windows Server 2012 R2
with Visual Studio 15.4.1
.
Can anyone reproduce this behaviour?
Can anyone confirm if my code is right or if there is any problems with it please?
Update After @ArhiChief suggested to test the results in the Release configuration, I figured that the problem only appears when I am using the IDE to debug my code.
When I build and run the code in the command line in either Debug/Release configuration, there seem to be no problems.
I tried to close/reopen the IDE and clean the project and do a fresh rebuild, and now the IDE seems to be working fine too.
Results: I haven't faced the issue so far after restarting the IDE, cleaning the project and doing a fresh rebuild of the project. I'm suspecting a minor bug in the IDE. However I can't report it because it has disappeared now.
I'm leaving this question open in case someone else encounters this issue and would want to track and report the bug.