注册 | 登录

解决c# - How do I access HttpContext.Current in Task.Factory.StartNew?

itPublisher 分享于




        最近做了一个在线支付,哎呀,把我给折腾的可不轻.搞了很长时间.    PayPal 是一家 eBay 公司,它是在线付款解决方案的全球领导者,在全世界有超过七千一

I want to access HttpContext.Current in my application within

Task.Factory.Start(() =>{
    //HttpContext.Current is null here

How can I fix this error?

c# .net c#-4.0
asked May 19 '12 at 5:03 Tim Tom 962 5 18 35


3 Answers


Task.Factory.Start will fire up a new Thread and because the HttpContext.Context is local to a thread it won't be automaticly copied to the new Thread, so you need to pass it by hand:

var task = Task.Factory.StartNew(
    state =>
            var context = (HttpContext) state;
            //use context

answered May 19 '12 at 5:09 nemesv 108k 10 279 283      interestingly enough, that does work strange for me. For example User property of HttpContext becomes null after entering the thread, although it had value in HttpContext.Current. –  Giedrius Apr 30 '13 at 15:02 2   Yes, it's worth noting that using a reference to HttpContext.Current might work a lot of the time but it's not recommended and it's likely to fail at times. ASP runtime may clean up the object when the http request is done and then you'll find things like context.Items[x] doesn't contain what you put there earlier. See also… –  Rory Dec 30 '15 at 17:22


You could use a closure to have it available on the newly created thread:

var currentContext = HttpContext.Current;

Task.Factory.Start(() => {
    // currentContext is not null here

But keep in mind that a task can outlive the lifetime of the HTTP request and could lead to funny results when accessing the HTTPContext after the request has completed.

推荐:How to convert XML to JSON in ASP.NET C#

原文: using System;using System.Collections;using System.Globalization;using System.Text;using System.Xml; /// <

answered May 19 '12 at 9:05 David Tischler 2,337 16 12      I like using this way instead of passing in a state object and casting the items out into individual variables... messy. –  The Muffin Man Jun 17 '15 at 21:56


As David pointed out, HttpContext.Current will not work all the time. In my case, about 1 of 20 time, CurrentContext will be null. End up with below.

string UserName = Context.User.Identity.Name;

System.Threading.Tasks.Task.Factory.StartNew(() =>
    UserName ...

answered Sep 28 '16 at 14:00 Rm558 639 8 21


推荐:Beginning ASP.NET in C#

Beginning ASP.NET in C# Part 1: Introducing .NET     Chapter 1: The Big Picture                                                Chapter 2: The C# Langu








您的注册邮箱: 修改

重新发送激活邮件 进入我的邮箱