Sandman
Sandman

Reputation: 94

HostingEnviroment.QueueBackgroundWorkItem works on localhost but cancels on IIS

I want the server to update a user by mail and because mailing takes around 5 seconds I want to run this on the background thread. The problem is IIS cancels my backgroundoperation before it can finish.

The following code works when I test in visual studio but doesn't work when I test on windows server:

HostingEnvironment.QueueBackgroundWorkItem(ct => ProgressMail(ct, smtpSend, emailMessage));

and my progressmail method is as follows:

private static void ProgressMail(CancellationToken ct, SmtpClient client, MailMessage message)
{
    try
    {
        ct.ThrowIfCancellationRequested();
        client.Send(message);
    }
    catch (Exception ex)
    {
        Log.Logger.Error("Error sending mail in background thread", ex);
    }
}

Microsoft documentation on msdn states the following:

Differs from a normal ThreadPool work item in that ASP.NET can keep track of how many work items registered through this API are currently running, and the ASP.NET runtime will try to delay AppDomain shutdown until these work items have finished executing. This API cannot be called outside of an ASP.NET-managed AppDomain. The provided CancellationToken will be signaled when the application is shutting down.

ASP.NET Runtime will try to delay shutdown. But its still shutting down. What am I doing wrong here? How can I force my application to keep running even when the request is finished.

Upvotes: 0

Views: 963

Answers (1)

Sandman
Sandman

Reputation: 94

Thanks to @Peit I knew to look more closely at SMTPClient and not at the HostingEnviroment.QueueBackgroundItem()

Problem was in sending email with SMTP on IIS. Had to add:

client.DeliveryMethod = SmtpDeliveryMethod.Network;

And now it's working on both localhost and IIS :)

Upvotes: 0

Related Questions