drexel sharp
drexel sharp

Reputation: 323

Web Service responds to caller while still processing thread

I am creating a web service
Inside the web service, I do some processing, which is very fast, I send 2 to 3 emails asynchronously using SmtpClient.SendAsync().

My problem is that even though they are being sent asynchronously, I have to wait for them to finish processing before ending the service and sending back a response to the user. If I don't wait for the SendCompletedEventHandler to fire, the email is never sent. Sometimes the mail server takes some time to respond.

The user doesn't really need to know if the emails were sent or not. It would be nice to just send the emails and let them process somewhere else and respond to the user as fast as I can.

Would anybody have a good solution for this? Maybe I'm wording my searches wrong but I'm not coming up with any solutions.

Upvotes: 3

Views: 1105

Answers (2)

Despertar
Despertar

Reputation: 22362

Here is a full example that I have tested and works with WCF. Control is returned immediately to the client, server starts sending, sleeps to simulate delay, then finishes. Just add a reference to System.ServiceModel to get the necessary classes.

class Program
{
    static void Main(string[] args)
    {
        ServiceHost host = new ServiceHost(typeof(HelloWorldService), new Uri("http://localhost:3264"));
        ServiceMetadataBehavior mdb = new ServiceMetadataBehavior();
        mdb.HttpGetEnabled = true;
        host.Description.Behaviors.Add(mdb);
        host.Open();

        Console.WriteLine("Service Hosting...");
        Console.ReadLine();
    }
}

[ServiceContract]
class HelloWorldService
{
    [OperationContract]
    public void SendEmails()
    {
        Task.Factory.StartNew(() =>
        {
            Console.WriteLine("Start Sending Emails...");
            Thread.Sleep(10000);
            Console.WriteLine("Finish Sending Emails...");
        });
    }
}

}

Upvotes: 0

Louis Somers
Louis Somers

Reputation: 2964

You could fire up a new thread to do the sending:

ThreadPool.QueueUserWorkItem(delegate {
    SmtpClient client = new SmtpClient();
    // Set up the message here
    using (MailMessage msg = new MailMessage()) {
        client.Send(msg);
    }
});

Upvotes: 1

Related Questions