I would suggest a solution different from the solution of Leon and David:
- David's solution is OK, but it is not sustainable. What is this instance / process disconnected during task processing?
- Leon's solution is mainly related to scheduled tasks, but sending email is not always planned (maybe you want to send an email when someone logs into your application).
Another option that you should pay attention to is to use the Windows Azure Storage Queues (which are very cheap) in this scenario:
- Your web application: sends messages to the queue (for example, "send an email to someone@someone.com ")
- WebRole.cs: create a new thread when you start the instance and ask him to listen to messages from this queue. Whenever a message arrives, process it. If successful, delete the message from the queue.
This solution has many advantages. WebRole.cs works in a different process than your web application, so it does not affect the flow of requests. And besides, if for some reason the sending of the mail failed, the message will remain in the queue and will be processed the next time. This ensures that you wonβt lose any tasks if the application or process crashes.
Here is an example to get you started. Please note that you need to improve this code if you want it to be ready for production (retry policy, exception handling, poll polling, ...):
using System; using System.Collections.Generic; using System.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Diagnostics; using Microsoft.WindowsAzure.ServiceRuntime; using Microsoft.WindowsAzure.StorageClient; using System.Threading.Tasks; namespace MvcWebRole1 { public class WebRole : RoleEntryPoint { public override bool OnStart() { Task.Factory.StartNew(InitializeQueueListener); return base.OnStart(); } private void InitializeQueueListener() { Microsoft.WindowsAzure.CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) => { configSetter(Microsoft.WindowsAzure.ServiceRuntime.RoleEnvironment.GetConfigurationSettingValue(configName)); }); var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString"); var queueStorage = storageAccount.CreateCloudQueueClient(); var queue = queueStorage.GetQueueReference("myqueue"); queue.CreateIfNotExist(); while (true) { CloudQueueMessage msg = queue.GetMessage(); if (msg != null) {
source share