0

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?

HJF
  • 3
  • 1
  • For getting access to `HttpContext` see this: https://stackoverflow.com/questions/10662456/how-do-i-access-httpcontext-current-in-task-factory-startnew – peeyush singh Apr 23 '19 at 06:52
  • 1
    Also files can be saved on the background thread as well, any need for it to be on main thread? – peeyush singh Apr 23 '19 at 06:53

1 Answers1

0

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);
Joey Phillips
  • 1,543
  • 2
  • 14
  • 22