c# excel beforesave thread

你说的曾经没有我的故事 提交于 2020-01-23 17:42:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!