问题
I try to create a c# excel 2007 Add-In, and i want to do "faster" the "beforeSave" method. I simply use a thread (and try the task and task.factory too) but its always say same error.
The code.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.WorkbookBeforeSave += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookBeforeSaveEventHandler(Application_WorkbookBeforeSave);
}// thisAddIn_startup method end
public void Application_WorkbookBeforeSave(Microsoft.Office.Interop.Excel.Workbook Wb, bool SaveAsUI, ref bool Cancel)
{
backendworker bwfs = new backendworker();// its a custom standalone class!
Task task1 = new Task(() => bwfs.MyBeforeSave(this.Application.ActiveWorkbook));
task1.Start();
}// application_workbookbeforesave method end
the backworker class:
public class backendworker
{
// BeforeSave method
public void MyBeforeSave(Microsoft.Office.Interop.Excel.Workbook Wb)
{
Wb.SaveCopyAs("c:\\temp\\temp.xls");
}// method end
}// class end
Without thread (any type) its okay, it can save the whole workbook. BUT. with any multithread soulution its throw error. (Exception from HRESULT: 0x800AC472)
Any idea what i do wrong? Or idea how to fix it? :D
回答1:
Interacting with Excel through multiple threads is a bit tricky -- here is an MSDN entry on it. This is because you interact with Excel through COM, which uses thread apartments; .NET, however, does not. In particular, Excel uses Single-Treaded Apartment (STA), which means that all new threads that are created for interacting with Excel must be set to STA state:
thread.SetApartmentState(ApartmentState.STA);
before interacting with Excel.
This still leaves a whole list of problems that may be encountered, as per the linked MSDN article. On the whole I would not advise interacting with Excel in multiple threads unless it's really necessary. There are no problems with background workers that don't interact with Excel, but interactions with Excel application through background threads is too troublesome to be worth it.
来源:https://stackoverflow.com/questions/11908397/c-sharp-excel-beforesave-thread