C#:工作簿的关闭方法不适用于在 OneDrive 上打开的工作簿

C# : Workbook's Close methods doesn't work for Workbook opened on OneDrive

我正在开发一个 VSTO 加载项,它调用当前工作簿上的 Microsoft.Office.Interop.Excel.Workbook.Close 方法以允许另一个进程在该文件上写入。

如果文件存储在本地,该方法会有效地关闭工作簿并将句柄从 EXCEL.EXE 锁定文件中释放出来。

但是,当文件保存在OneDrive上时,Close方法似乎没有作用。那是一个错误吗?有什么想法吗?

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
     this.Application.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);
}
        
void Application_WorkbookOpen(Excel.Workbook Wb)
{
     Wb.Close(); // doesn't work for oneDrive files ?!
}

除了延迟之外,尝试 运行 垃圾收集器清扫堆并释放关闭工作簿后未使用的 COM 引用。注意,需要调用两次GC:

GC.Collect
GC.WaitForPendingFinalizers
GC.Collect
GC.WaitForPendingFinalizers

When to release COM objects in Office add-ins developed in .NET 文章中阅读更多相关信息。

此外,您可能会发现 Why doesn’t Excel quit? 文章很有帮助。

@Joseph (Thread + Timing idea) 和@Eugene (CG idea) 的回答让我找到了解决方案!这是代码:

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
     this.Application.WorkbookOpen += new Excel.AppEvents_WorkbookOpenEventHandler(Application_WorkbookOpen);
}
        
void Application_WorkbookOpen(Excel.Workbook Wb)
{
     // Wb.Close(); // DOESN'T WORK
     Thread t = new Thread(() => this.ReleaseWorkbook(ref Wb)); // ReleaseWorkook doesn't work in the current thread
     t.Start();
}

void ReleaseWorkbook(ref Excel.Workbook Wb)
{
    Wb.Close(false, Type.Missing, Type.Missing); 
    Wb = null; 
    GC.Collect();
    GC.WaitForPendingFinalizers();
    GC.Collect();
    GC.WaitForPendingFinalizers();
}