2

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

                }
noseratio
  • 59,932
  • 34
  • 208
  • 486
VVR147493
  • 251
  • 2
  • 4
  • 16
  • Next time please try to do better job on the post and code formatting: http://stackoverflow.com/help/formatting – noseratio Apr 23 '14 at 13:10

1 Answers1

5

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());
noseratio
  • 59,932
  • 34
  • 208
  • 486
  • Thanks Noseratio. When I add the above I got the error function StartNew cannot acccept the second parameter TaskScheduler.FromCurrentSynchronizationContext(). I am using MVC4 in VS2010 SP1. – VVR147493 Apr 24 '14 at 14:41
  • 1
    Thanks Noseratio. Working like a charm. – VVR147493 May 01 '14 at 11:38