demo
demo

Reputation: 6245

HttpContext becomes NULL in Tasks

I create extension method for HttpContext. This method generates pdf files.

public static Task GeneratePdfTask(this HttpContext context, string path, int submissionId, string pdfName, Action<int, byte[]> postAction = null)
    {
        var local = context;
        return Task.Factory.StartNew(() =>
        {
            HttpContext.Current = local;
            SessionHelper.Set(SessionKey.IsPdfRendering, true);
            var pdfFile = new PdfGenerator().Generate(path, pdfName, submissionId);
            if (postAction != null && pdfFile != null)
            {
                postAction(submissionId, pdfFile);
            }
        });
    }

Sometimes this Session (HttpContext.Current) become NULL and i get exception. But don't know why. Is there some restriction of creating extensions for Session? Maybe there are some another solution how to safely use current Session?

Upvotes: 2

Views: 2239

Answers (1)

usr
usr

Reputation: 171246

You can't use HTTP request objects concurrently from multiple threads so this question is moot. Pass the data you want to move across threads explicitly.

To explain what you are seeing: HttpContext.Current is dependent on the current thread (actually it's the logical call context). Don't set it to some value. You have now hijacked the HttpContext.Current of some innocent unrelated thread-pool thread. You might now find that different HTTP requests start to interact. Those are hard and nasty bugs to find.

Upvotes: 1

Related Questions