Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8978313
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T19:34:49+00:00 2026-06-15T19:34:49+00:00

I have a long-running asynchronous task that is kicked off from an ASP.NET MVC4

  • 0

I have a long-running asynchronous task that is kicked off from an ASP.NET MVC4 web page. The controller method looks like this:

[HttpPost]
public ActionResult Index(IndexModel model)
{
    if (ModelState.IsValid)
    {
        try
        {
            model.NotificationRecipient = model.NotificationRecipient.Replace(';', ',');
            ImportConfiguration config = new ImportConfiguration()
            {
                BatchId = model.BatchId,
                ReportRecipients = model.NotificationRecipient.Split(',').Select(c => c.Trim())
            };
            System.Threading.ThreadPool.QueueUserWorkItem(foo => LaunchFileImporter(config, this.HttpContext.ApplicationInstance.Context));
            if (model.RunExport) ThreadPool.QueueUserWorkItem(foo => LaunchFileExporter());
            Log.InfoFormat("Queued the ImportProcessor to process invoices.  Send Notification: {0} Email Recipient: {1}",
                model.SendNotification, model.NotificationRecipient);
            TempData["message"] = "The import processor job has been started.";
            //return RedirectToAction("Index", "Home");
        }
        catch (Exception ex)
        {
            Log.Error("Failed to properly queue the invoice import job.", ex);
            ModelState.AddModelError("", ex.Message);
        }
    }

    var dirInfo = new System.IO.DirectoryInfo(dir);
    model.Files = dirInfo.EnumerateFiles("*.xml").OrderBy(x => x.Name.ToLower());

    return View(model);
}

My LaunchFileImporter method looks like this:

private void LaunchFileImporter(ImportConfiguration config, System.Web.HttpContext context)
{
    //the semaphore prevents concurrent running of this process, which can cause contention.
    Log.Trace(t => t("submitter semaphore: {0}", (exporter == null) ? "NULL" : "present."));
    submitter.WaitOne();
    try
    {
        Log.Trace(t => t("Context: {0}", context));
        using (var processor = new ImportProcessor(context))
        {
            processor.OnFileProcessed += new InvoiceFileProcessing(InvoiceFileProcessingHandler);
            processor.OnInvoiceProcessed += new InvoiceSubmitted(InvoiceSubmittedHandler);
            processor.Execute(config);
        }
    }
    catch (Exception ex)
    {
        Log.Error("Failed in execution of the File Importer.", ex);
    }
    submitter.Release();
}

My Logger is a Common.Logging private static readonly ILog, and is configured for NLog. It seems properly wired up; at least, I get a fair amount of logs out of it.

Here’s the thing: The moment I hit System.Threading.ThreadPool.QueueUserWorkItem, the application pool death spirals into a silent death, resetting the app pool, reloading the membership provider, reprocessing the web.config, the whole shebang… No YSOD, no indication on the web page… everything just quietly blows up. The last log entry I get is Queued the ImportProcessor to process invoices....

I should note the page does the refresh. The TempData["message"] is populated and displayed on the screen, which makes me believe the problem is happening in the asynchronous process… but pretty much immediately. Due to the lack of additional logs I am assuming there is a problem with the logger.

So I’m hoping someone can either tell me what is happening, point to some documented issue with this, tell me how I’m being an idiot, or reproduce something similar as a bug.

Thanks!

UPDATE

@RichardDeeming pointed out that the context information was not getting into the spawned thread, and this seemed to be the cause of the problem. I still haven’t wrapped my brain around why this didn’t work nor did it write the trace messages, but once I captured the part of the context that I needed, the IPrincipal, and used that instead of the context object, it just worked.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T19:34:50+00:00Added an answer on June 15, 2026 at 7:34 pm

    You’ll get a NullReferenceException in the line:

    ThreadPool.QueueUserWorkItem(foo => LaunchFileImporter(config, HttpContext.ApplicationInstance.Context));
    

    The HttpContext gets cleaned up once the request has completed. Since the exception is thrown on a background thread, it will bring down the whole AppDomain, causing your application to restart.

    You need to capture the relevant state from the context in the controller action, and use that state in the WaitCallback delegate:

    IPrincipal user = Context.User;
    ThreadPool.QueueUserWorkItem(foo => LaunchFileImporter(config, user));
    
    // Or:
    // ThreadPool.QueueUserWorkItem(state => LaunchFileImporter(config, (IPrincipal)state);
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We have an asynchronous task that performs a potentially long-running calculation for an object.
I have a long running task that benefits from multithreading. A L2S entity is
i have long running task that gets called using jquery ajax. i am using
Basically I have the problem of a long running task in my web application.
I am using ExtJS 3.4. I have a long running asynchronous process that I
I have a ASP.NET web application running on an IIS6 server. The application is
I have a long running task that I want completed, even if the application
I have a particularly long running method that I need to execute from my
I have a long running (4-10 second) MVC action that runs a report from
I have a long running task that must be guided by external code. But

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.