I am using TPL to create new tasks in my code. All works well with improved performance. but whenever there is HTTPContext object like context.currentuser.iDentifier. this code throws an exception saying HTTP Context object not available. Null reference exception. I want to know how to pass the context object to the task object?
Asked
Active
Viewed 268 times
3
-
Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – rene Jan 13 '17 at 11:23
-
HttpContext.Current is not null only if you access it in a thread that handles incoming requests. With TPL you code can be executed in different thread. Details - http://stackoverflow.com/questions/19509672/why-is-httpcontext-current-null – Nikolay Jan 13 '17 at 11:27
-
@rene, this is not duplicate. the question you referred to is generic .NET framework null reference exception. – kevalsing Jan 13 '17 at 11:31
-
It is a perfect duplicate. This error is so common, we are not going to debug every single occurrence of it. Specially if you don't have an [MCVE]. – rene Jan 13 '17 at 11:33
-
I am not asking to debug. I just wanted to know why this occurs and how to pass context object. – kevalsing Jan 13 '17 at 14:00
1 Answers
5
This is because the parallel thread is not executing in the same context. You need to pass the SynchronizationContext it.
In TPL you can use TaskScheduler.FromCurrentSynchronizationContext()
to pass the context.
In one of my project I have done it something like this -
Task.Factory.StartNew(() => MyMethod(),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.FromCurrentSynchronizationContext());

Yogi
- 9,174
- 2
- 46
- 61