Pergunta

I am currently working on MVC4 in VS2010-SP1. I made one of the function in the controller class Asynchronous. As part of that I made the controller class derived from AsyncController and added the below two methods ( see code section 1 and 2 below). one method ending with Async(See Code Section 1 ) and another method ending with Completed ( See Code Section 2 ). The problem is in the model class I am trying to access my webservice with credentials from HttpContext ( See Code below 3 ). The context is going null when making an asynchronous call. ie, In the new thread httpcontext is not available. How to pass the context from main thread to 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;
                }
                finally
                {
                    WcfClient.CloseWebServiceConnection<ReportReadingClient, 
IReportReading> (client);
                }

                }
Foi útil?

Solução

HttpContext.Current is null because your task is executed on a 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());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top