Home > Uncategorized > Handling the effect of HttpContext null in a separate thread in ASP.NET

Handling the effect of HttpContext null in a separate thread in ASP.NET

If you have an ASP.NET page that needs to respond quickly, but perhaps has a slow background task to do, that would be ideal to perform in a background thread. However, suddently you find that HttpContext is null, so you can no longer access server features in the background thread.

The case could be a webhook, where a third party calls your server, and has a timeout of a few seconds before they kill the connection to your server. but you have some large processing to do, that won’t be done in time, or potentially won’t be done in time.

Otherwise, it could be just a performance optimization, you have a few things you need the user to see, but there are other tasks that can happen in the background, that the user doesn’t need to wait for.

Here’s the problematic code:

    protected void Page_Load(object sender, EventArgs e)
    {
      
        var asyncJob = new Thread(() => HandleJob());
        asyncJob.Start();
    }

    private static void HandleJob()
    {
        DoSomeLongRunningTask(HttpContext.Current.Request.QueryString["jobId"]);
    }

But this code fails, because HttpContext.Current will be null in the context of the thread. It also will fail silently, since the page will load fine.

The Fix? – move any variables that you might need to access outside of the Thread

    protected void Page_Load(object sender, EventArgs e)
    {
        var jobId = Request.QueryString["jobId"];
        var asyncJob = new Thread(() => HandleJob(jobId));
        asyncJob.Start();
    }

    private static void HandleJob(string JobId)
    {
        DoSomeLongRunningTask(JobId);
    }

Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment