asp.net mvc 4 - HttpContext.Current null when making a function Asynchronous in MVC4 -


i working on mvc4 in vs2010-sp1. made 1 of function in controller class asynchronous. part of made controller class derived asynccontroller , added below 2 methods ( see code section 1 , 2 below). 1 method ending async(see code section 1 ) , method ending completed ( see code section 2 ). problem in model class trying access webservice credentials httpcontext ( see code below 3 ). context going null when making asynchronous call. ie, in new thread httpcontext not available. how pass context main thread new threads created.

code section 1

public void sendplotdatanewasync(string fromdate, string todate, string item) {           asyncmanager.outstandingoperations.increment();                     var highchartmodel = new highchartviewmodel();                     task.factory.startnew(() =>                     {                           asyncmanager.parameters["dataplot"] =  highchartmodel.getgraphplotpointsnew(fromdate, todate, item);                           asyncmanager.outstandingoperations.decrement();                       });  } 

code section 2

 public jsonresult sendplotdatanewcompleted(dictionary<string, list<chartdata>>   dataplot)  {       return json(new { data = dataplot });  } 

code section 3

public list<meterreportdata> getmeterdatapointreading(meterreadingrequestdto  meterplotdata) {              var client = wcfclient.openwebserviceconnection<reportreadingclient,    ireportreading>(null, (string)httpcontext.current.session["webservicecredentials"] ??  string.empty);                  try                 {                     return  readreportmapper.meterreportreadmap(client.getmeterdatapointreading(meterplotdata));                 }                 catch (exception ex)                 {                     log.error("metadata exception:{0},{1},{2},{3}",  ex.gettype().tostring(), ex.message, (ex.innerexception != null) ?  ex.innerexception.message : string.empty, " ");                     throw;                 }                                 {                     wcfclient.closewebserviceconnection<reportreadingclient,  ireportreading> (client);                 }                  } 

httpcontext.current null because task executed on pool thread without aspnetsynchronizationcontext synchronization context.

use taskscheduler.fromcurrentsynchronizationcontext():

task.factory.startnew(() =>     {         asyncmanager.parameters["dataplot"] =             highchartmodel.getgraphplotpointsnew(fromdate, todate, item);         asyncmanager.outstandingoperations.decrement();     },     cancellationtoken.none,     taskcreationoptions.none,      taskscheduler.fromcurrentsynchronizationcontext()); 

Comments

Popular posts from this blog

java - Intellij Synchronizing output directories .. -

git - Initial Commit: "fatal: could not create leading directories of ..." -