【发布时间】:2014-04-23 11:01:34
【问题描述】:
我目前正在 VS2010-SP1 中开发 MVC4。我做了一个功能 控制器类异步。作为其中的一部分,我制作了控制器类 派生自 AsyncController 并添加了以下两个方法(参见代码部分 1 和 2 下)。一种以 Async 结尾的方法(参见代码第 1 节)和另一种以 Async 结尾的方法 已完成(参见代码第 2 节)。问题出在我正在尝试的模型类中 使用来自 HttpContext 的凭据访问我的网络服务(请参见下面的代码 3)。这 进行异步调用时上下文为空。即,在新线程中 httpcontext 不可用。如何将上下文从主线程传递到新线程 已创建。
代码部分 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();
});
}
代码第 2 节
public JsonResult SendPlotDataNewCompleted(Dictionary<string, List<ChartData>>
dataPlot)
{
return Json(new { Data = dataPlot });
}
代码第 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);
}
}
【问题讨论】:
-
下次请尽量在帖子和代码格式方面做得更好:stackoverflow.com/help/formatting
标签: asp.net-mvc-4 asynchronous task-parallel-library