Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why httpcontext object is not available while using task parallel library task?

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?

like image 604
kevalsing Avatar asked Sep 03 '25 08:09

kevalsing


1 Answers

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());
like image 142
Yogi Avatar answered Sep 05 '25 00:09

Yogi