C#中脱颖而出beforesave线程

C#中脱颖而出beforesave线程

本文介绍了C#中脱颖而出beforesave线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个C#Excel 2007中加载项,和我想要做的更快的beforeSave的方法。
我简单地使用一个线程(并尝试过的任务和task.factory),但其总是说同样的错误。

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.

中的代码。

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



backworker类:​​

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



无螺纹(任何类型)的好,它可以保存整个工作簿。
,而。与任何多线程soulution它扔错误。 (从HRESULT异常:0x800AC472 的)

任何想法,我做错了什么?或者知道如何解决它? :D

Any idea what i do wrong? Or idea how to fix it? :D

推荐答案

通过多线程与Excel的交互是有点棘手 - 是它的MSDN项。这是因为你用Excel通过COM,它采用螺纹式公寓交互; .NET,但是,其实不然。特别是,Excel使用单处治公寓(STA),这意味着,与Excel交互创建的所有新的线程必须设置为STA状态:

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);



与Excel交互之前。

before interacting with Excel.

这还剩下的可能遇到的,按照链接的MSDN文章的问题的完整列表。整体上的我不建议在多线程与Excel交互,除非真的有必要。有背景的工人没有问题,不与Excel交互,而是通过后台线程与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.

这篇关于C#中脱颖而出beforesave线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 19:09