I've seen similar questions (here and here for instance), but I'm still not sure why my code is behaving the way it is. I'm writing some unit tests that do some thread specific work with async functions, but the problem is that the thrown exception isn't caught. Here's a simple example of what I mean:
static void Main(string[] args)
{
ExecuteWillCatch(async () =>
{
await MyTaskFunction();
throw new Exception("I throw an exception");
});
}
static void MyAction()
{
MyTaskFunction();
throw new Exception("I throw an exception!");
}
static async Task MyTaskFunction()
{
}
static void ExecuteWillCatch(Action action)
{
var op = new ThreadStart(() =>
{
try
{
action.Invoke();
}
catch (Exception e)
{
Console.WriteLine("I caught the exception");
}
});
var thread = new Thread(op);
thread.Start();
thread.Join();
}
If I use an async
lambda in my Test, then what happens is the Exception is thrown at the expected target, and then rethrown in mscorlib, and subsequently not caught in the try-catch block in ExecuteWillCatch. If I replace the async/await with just waiting for a result, everything will pass. That's a workaround that I can use, but I'd like to ideally test the code as it will be used (with the async/await).
I've also tried putting try-catch blocks in the Main function, and around the thread calls, thinking that maybe the exception is thrown back to that thread, but that isn't the case either.
Can anyone suggest a way to do this, or explain why it doesn't work?