Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 关闭Excel工作簿时出现异常_C#_Multithreading_Interop_Comexception - Fatal编程技术网

C# 关闭Excel工作簿时出现异常

C# 关闭Excel工作簿时出现异常,c#,multithreading,interop,comexception,C#,Multithreading,Interop,Comexception,我正在使用Excel=Microsoft.Office.Interop.Excel将各种数据写入Excel工作表 Excel.Workbook wb = null; Excel.Worksheet ws = null; Excel.Application excelApp = new Excel.Application(); excelApp.Visible = true; try { // Create new workbook wb = (Excel.Workbook)(

我正在使用
Excel=Microsoft.Office.Interop.Excel
将各种数据写入Excel工作表

Excel.Workbook wb = null;
Excel.Worksheet ws = null;

Excel.Application excelApp = new Excel.Application();
excelApp.Visible = true;

try {
    // Create new workbook
    wb = (Excel.Workbook)(excelApp.Workbooks.Add(Type.Missing));
    ws = wb.ActiveSheet as Excel.Worksheet;

    // write data ...

    // Save & Close
    excelApp.DisplayAlerts = false; // Don't show file dialog for overwrite
    wb.Close(true, targetFilename, Type.Missing);

} finally {
    // Close the Excel process
    if (null != ws)
        Marshal.ReleaseComObject(ws);
    if (null != wb)
        Marshal.ReleaseComObject(wb);
    excelApp.Quit();
    Marshal.ReleaseComObject(excelApp);
    GC.Collect();
}
这段代码一次由多个线程执行,而且几乎一直在工作。甚至Excel进程也会在task manager中消失

但是,有时会在wb.Close(true,targetFilename,Type.Missing)处抛出
System.Runtime.InteropServices.COMException
。它声称对目标文件名的访问被拒绝。尽管我一直在确保目标文件名是唯一的


异常可能是由于Excel处理不当,或者我正在使用线程造成的?

显然,targetFilename并不是唯一的。在大小写拼写上只有一个区别,似乎两个线程试图同时写入同一个文件。使用
targetFilename.ToLower()
可以轻松解决此问题

无论如何,如果您发现任何进一步的潜在问题,请留下评论