kevalsing
kevalsing

Reputation: 437

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?

Upvotes: 3

Views: 283

Answers (1)

Yogi
Yogi

Reputation: 9739

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());

Upvotes: 5

Related Questions