简体   繁体   中英

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:

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. How can I accomplish this?

Task.Factory.Start will fire up a new Thread and because the HttpContext.Context is local to a thread it won't be automaticly copied to the new Thread, so you need to pass it by hand:

var task = Task.Factory.StartNew(
    state =>
        {
            var context = (HttpContext) state;
            //use context
        },
    HttpContext.Current);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM