I have a method that repeats work using a task and asynchronously / waits.
public static Task ToRepeatingWork(this Action work, int delayInMilliseconds)
{
Action action = async () =>
{
while (true)
{
try
{
work();
}
catch (MyException ex)
{
}
await TaskEx.Delay(new TimeSpan(0, 0, 0, 0, delayInMilliseconds));
}
};
return new Task(action, SomeCt, TaskCreationOptions.LongRunning);
}
I wrote the corresponding test:
[TestMethod, TestCategory("Unit")]
public async Task Should_do_repeating_work_and_rethrow_exceptions()
{
Action work = () =>
{
throw new Exception("Some other exception.");
};
var task = work.ToRepeatingWork(1);
task.Start();
await task;
}
I expect this test to fail, but it will pass (and the test runner will fail).
However, if in the ToRepeatingWork method I change the action from async to the normal action and use Wait instead of waiting, the test behaves as expected.
TaskEx.Delay(new TimeSpan(0, 0, 0, 0, delayInMilliseconds)).Wait();
What is wrong here?
source
share