views:

263

answers:

7

Hi,

I have a simple function that sends out emails, how would I go about using threads to speed email delivery?

Sample code would be ideal.

+8  A: 

Use SendAsync isntead.

leppie
A: 

Create your class with a static void method that will make your class start doing what you want to do on the separate thread with something like:

using System;
using System.Threading;

class Test
{
    static void Main() 
    {
        Thread newThread =  new Thread(new ThreadStart(Work.DoWork));
        newThread.Start();
    }
}

class Work 
{
    Work() {}
    public static void DoWork() {}
}

Another alternative is to use the ThreadPool class if you dont want to manage your threads yourself.

More info on Threads - http://msdn.microsoft.com/en-us/library/xx3ezzs2.aspx

More info on ThreadPool - http://msdn.microsoft.com/en-us/library/3dasc8as(VS.80).aspx

Wolfwyrd
+1  A: 

Having a seperate thread will not speed the delivery of email however. All it will do is return control back to the calling method faster. So unless you need to do that, i wouldnt even bother with it.

mattlant
A: 

You know what would be nicer and easier is to create an application back end and send emails every 30 minutes. Throw the information into a database that you need to send to and from there, create an application pool that launches every 30 minutes. When it launches, you can send an email. No need to wait for your event handler to send the email...

It works for us. Just thought it would help for you.

Scott
+2  A: 

Check out the following link for a demonstration of the sendAsync method. [MSDN]

http://msdn.microsoft.com/en-ca/library/x5x13z6h(VS.80).aspx

chris
A: 

You can run the function in another thread. Being SendMail your mail sender function you can:

ThreadPool.QueueUserWorkItem(delegate { SendMail(message); });
Eduardo Campañó
A: 

When you send e-mails using multiple threads, be careful about getting identified as spam by your isp. It will be better to opt for a smaller batches with some delay between each batch.

Vijesh VP