Interesting problem with SmtpClient in background thread

M

mark.lees

I'm experimenting with the SmtpClient class in c# and I have run into a
knotty 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", "(e-mail address removed)", "This is a queued test
message", "hello world again" );
}
}
 
M

mark.lees

!! 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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top