|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Interesting problem with SmtpClient in background threadknotty problem. I'm using the ThreadPool.QueueUserWorkItem to queue a delegate which creates an SmtpClient and attempts to send an email. Basically, If I try and create a new SmtpClient object in a thead managed by the threadpool the application exits without an exception being thrown/caught. However, if I create an SmtpClient in the main program the pooled thread can create the SmtpClient but it then blows up trying to send an email.... Anyone got any ideas..... I'm using the following code public class MailServer { public void QueueMail( string from, string to, string subject, string body ) { MailMessage m = new MailMessage( from, to, subject, body ); ThreadPool.QueueUserWorkItem( new WaitCallback( MailProc ), m ); } static void MailProc( object state ) { SmtpClient clt = null; try { clt = new SmtpClient( "InternalMailServer" ); // <<---- The application blows up here without being caught !! } catch ( Exception e ) { Console.WriteLine( e.Message ); } try { clt.Send( (MailMessage)state ); } catch ( Exception e ) { Console.WriteLine( e.Message ); } } } class Program { static void Main( string[] args ) { // SmtpClient clt = new SmtpClient( "InternalMailServer" ); // <<--- Is I uncomment this line it blows up at the Send() above.... MailServer m = new MailServer(); m.QueueMail( "from@fromcom", "t*@to.com", "This is a queued test message", "hello world again" ); } } !! Doh !!!!
The main application thread is exiting before the background threads in the threadpool have had a chance to finish.... The threadpool creates Background worker threads which die as soon as the main application thread terminates.... Does anyone know how I can wait for the background threads to exit before I allow the main application thread to terminate.... M. |
|||||||||||||||||||||||