I have a method which does repeating work using a task and async/await.
public static Task ToRepeatingWork(this Action work, int delayInMilliseconds)
{
Action action = async () =>
{
while (true)
{
try
{
work();
}
catch (MyException ex)
{
// Do Nothing
}
await TaskEx.Delay(new TimeSpan(0, 0, 0, 0, delayInMilliseconds));
}
};
return new Task(action, SomeCt, TaskCreationOptions.LongRunning);
}
I have written a 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 am expecting this test to fail, but it passes (and crashes the test-runner).
However if in the ToRepeatingWork method, I change the action from async to a normal action and use Wait instead of await, the test behaves as expected.
TaskEx.Delay(new TimeSpan(0, 0, 0, 0, delayInMilliseconds)).Wait();
What is wrong here?