[英]How to run a statement on the main thread from a task
I create a task as below: 我创建了一个如下任务:
ExportTask = Task.Factory.StartNew(() => ExcelExport(rs, ReportCenter));
Inside the ExcelExport() method I like to run a statement that will save an excel spreadsheet, but it needs to be on the main thread: 在ExcelExport()方法内部,我喜欢运行一个保存excel电子表格的语句,但它需要在主线程上:
workbook.SaveAs(String.IsNullOrWhiteSpace(AppSettingsUtils.GetString("ExportExcelFileName")) ? "Export.xlsx" : AppSettingsUtils.GetString("ExportExcelFileName"), Response, ExcelDownloadType.PromptDialog, ExcelHttpContentType.Excel2013);
For that matter I'm curious on how to get a value from a statement such as this in a task as well: 就此而言,我很好奇如何在任务中从这样的语句中获取值:
ReportCenter = HttpContext.Current.Profile.GetPropertyValue("ReportCenter");
Seems to be a lot of info on windows forms but having trouble finding for web forms. 似乎是Windows窗体上的很多信息,但无法找到Web表单。 How can I accomplish this? 我怎么能做到这一点?
Task.Factory.Start
will fire up a newThread
and because theHttpContext.Context
is local to athread
it won't be automaticly copied to the new Thread, so you need to pass it by hand:Task.Factory.Start
将启动一个新的Thread
,因为HttpContext.Context
是一个thread
本地,它不会被自动复制到新的Thread,所以你需要手动传递它:
var task = Task.Factory.StartNew(
state =>
{
var context = (HttpContext) state;
//use context
},
HttpContext.Current);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.