In my code I assume that outerFlag
will be hit after innerFlag
but it actually runs like fire and forget (innerFlag
is hit after outerFlag
). When I use Thread.Sleep
instead of Task.Delay
flags are hit in correct order.
Here is the code:
[Test]
public async Task Test() {
bool innerFlag = false;
bool outerFlag = false;
await Lock(async () => {
await Task.Delay(2000);
innerFlag = true;
});
outerFlag = true;
Thread.Sleep(1000);
Thread.Sleep(2500);
}
private Task Lock(Action action) {
return Task.Run(action);
}
I also noticed that when I call Task.Delay
and set innerFlag
without a Lock
method but by direct lambda, it works as expected.
Can somebody explain such behaviour?