I am very new with this async/await concept, so I apologise for asking anything that is obvious.
I need to send email and the new API require me to use async and await. Problem is that a lot of my methods need to call this "send email" synchronously.
So, I create a synchronous wrapper method:
private Task SendEmailAsync(string email, string content)
{
...
...
...
}
private void SendEmail(string email, string content)
{
Task tsk = Task.Factory.StartNew(async () => await SendEmailAsync(email, content));
try { tsk.Wait(); }
catch (AggregateException aex)
{
throw aex.Flatten();
}
}
But for some reason, tsk.Wait() does not waiting for await SendEmailAsync(...) to finish. So, I need to add ManualResetEvent
. Something like this
private void SendEmail(string email, string content)
{
ManualResetEvent mre = new ManualResetEvent(false);
Task tsk = Task.Factory.StartNew(async () =>
{
mre.Reset();
try { await SendEmailAsync(email, content); }
finally { mre.Set(); }
});
mre.WaitOne();
try { tsk.Wait(); }
catch (AggregateException aex)
{
throw aex.Flatten();
}
}
But any exception thrown by SendEmailAsync(...) will NOT be captured by tsk.Wait(). My question is:
- Why tsk.Wait() does NOT wait for await SendEmailAsync(...)
- How to catch exception thrown by await SendEmailAsync(...)
Thanks!