I have a long chain of calls that eventually calls an asynchronous function in another assembly. I want this function to be executed synchronously, and it may throw an exception, which I want to propagate up the call chain.
This scenario is minimally reproduced by the following snippet:
static Task<int> Exc()
{
throw new ArgumentException("Exc");
return Task.FromResult(1);
}
static async void DoWork()
{
await Exc();
}
static void Main(string[] args)
{
try
{
DoWork();
}
catch (Exception e)
{
Console.WriteLine("Caught {0}", e.Message);
}
}
This code will cause a crash, because the exception thrown from Exc
doesn't get propagated back to Main
.
Is there any way for me to have the exception thrown from Exc
be handled by the catch block in Main
, without changing every function in my call chain to use async
, await
, and return a Task
?
In my actual code, this asynchronous function is called from a very deep chain of function calls, all of which should executed synchronously. Making them all asynchronous when they'll never be used (nor can they be safely used) asynchronously seems like a terrible idea, and I'd like to avoid it, if possible.