(I am still in early stage of learning async-await
and Task Parallel Library.)
I was asked to add some functionality to our existing project: send out email notification when system gets important data.
// part of API; called by other parts of the program
public override void PrivateSignal(IEventInformation ev)
{
// ... some light CPU processing of data
// will do some IO bound (non-CPU bound) processing
// in my case, send out email notification
// using `System.Net.Mail.SmtpClient`class
smptClient.SendMail(CaptureRC.SmptFromEmailAddr,
ToEmails, CaptureRC.EmailSubject,
"seen moving" + tag.ToString());
}
According to answers to my previous questions and blog post by Stephen Cleary, following construct is not a good choice to make my code "asynchronous":
public override void PrivateSignal(IEventInformation ev) {
Task.Run(async ()=>{await smptClient.SendMailAsync(....);}).Wait();
}
Assume for the moment that PrivateSignal()
was called 50 times in a row, and I would make IO operation synchronous:
public override void PrivateSignal(IEventInformation ev) {
Task.Run(()=>{ smptClient.SendMail(....);}).WaitAll();
}
This will create 50 threads in the pool, and each one of them will be blocked by synchronous call, in addition, .WaitAll()
will block running thread (I can get rid of .WaitAll()
since return from SendMail() is void). Overall, 51 threads stuck, doing nothing.
What could be possible be done to improve IO operation without wasting so much time and resources ?