I have a test and I want to make sure that I will get isolated result per Thread from an async
method. My test is look like the following:
public async Task MyMethod_Concurrency_ReturnsIsolatedResultPerThread()
{
int expectedResult = 20;
var theMock = new Mock<IService>();
theMock.Setup(m => m.GetResult(It.IsAny<int>()))
.Callback(() => Thread.Sleep(10))
.Returns<int>(t => Task.FromResult(expectedResult));
var sut = new MyClass(30, theMock.Object);
var rs1 = new ManualResetEventSlim();
var rs2 = new ManualResetEventSlim();
var task1 = Task.Run(async () =>
{
expectedResult = 40;
await sut.MyMethod();
rs2.Set();
rs1.Wait();
Assert.AreEqual(expectedResult, sut.Result);
});
var task2 = Task.Run(async () =>
{
rs2.Wait();
expectedResult = 45;
await sut.MyMethod();
Assert.AreEqual(expectedResult, sut.Result);
rs1.Set();
});
var task3 = Task.Run(() => Assert.AreEqual(0, sut.Amount));
await Task.WhenAll(task1, task2, task3);
}
The test works fine and passed successfully. However without using ManualResetEventSlim
it also works as expected. So my question is what is the usage of ManualResetEventSlim
in this example? I'm really confused with that? Can anybody please explain what is difference between using ManualResetEventSlim
or not using it in my test? What can I do, so that my test won't be passed without using ManualResetEvents
??