gpt4 book ai didi

c# Excel Interop 等待处理 0x800AC472 错误的替代方法

转载 作者:行者123 更新时间:2023-11-30 12:18:17 26 4
gpt4 key购买 nike

我有一个应用程序多次写入公式/宏加载工作簿。它循环遍历一些数据 3 次,创建、填充、保存,然后在每次迭代中关闭 excel 文件。虽然当它是其自身运行的唯一版本时它工作正常,但如果它有多个实例在运行,它就会出现问题。

具体来说,我在向某些单元格写入数据时遇到 0x800AC472 错误。每次都不是相同的单元格或值,但它似乎每次都在第二次通过。这是相关代码:

public void SetCellValue(int row, int col, string val)
{
if (_currWorkSheet != null)
{
string parms = string.Format("row={0}; col={1}; val={2}", row.ToString(), col.ToString(), val);
for (short i = 0; i < _maxRetries; i++)
{
try { (_currWorkSheet.Cells[row, col] as Range).Value2 = val; return; }
catch (Exception ex) { HandleError(ex, parms); }
}
Exception newExc = new Exception("Too many retries attempting to set cell value.");
newExc.Data.Add("parms", parms);
throw newExc;
}
}


private void HandleError(Exception exc, string parms)
{
if (exc != null && exc.Message != null)
{
// Excel error that just needs more time to complete. http://social.msdn.microsoft.com/forums/en-US/vsto/thread/9168f9f2-e5bc-4535-8d7d-4e374ab8ff09/
if (exc.Message.Contains("0x800AC472"))
Thread.Sleep(_threadSleepMs); // Give excel a chance to catch up, then keep processing.
else
{
Exception newExc = new Exception("Unexpected Error", exc);
newExc.Data.Add("parms", parms);
throw newExc;
}
}
}

我已将 _maxRetries 设置为 10,将 _threadSleepMs 设置为 500 并继续出现错误,因此我认为再增加它没有意义。

我想知道是否有其他方法可以让线程休眠以使其有机会“摆脱”原来的状态。

也许这可以作为第二个问题,但我并不那么担心,但是,当它崩溃时,我仍然在 finally block 中对它执行 Close(),但我仍然有它的实例徘徊。这是我关闭它的方式:

public void Dispose()
{
if (!_disposed)
{
if (_currWorkBook != null)
for (short i = 0; i < _maxRetries; i++)
{
try { _currWorkBook.Close(false, _missing, _missing); break; }
catch (Exception ex) { HandleError(ex, ""); }
}

if (_app != null)
{
if (_app.Workbooks != null)
for (short i = 0; i < _maxRetries; i++)
{
try { _app.Workbooks.Close(); break; }
catch (Exception ex) { HandleError(ex, ""); }
}

for (short i = 0; i < _maxRetries; i++)
{
try { _app.Quit(); break; }
catch (Exception ex) { HandleError(ex, ""); }
}

if (_currWorkSheet != null)
{
Marshal.ReleaseComObject(_currWorkSheet);
_currWorkSheet = null;
}
if (_currWorkBook != null)
{
Marshal.ReleaseComObject(_currWorkBook);
_currWorkBook = null;
}
Marshal.ReleaseComObject(_app);
_app = null;
}

GC.Collect();
_disposed = true;
}
}

它没有抛出和错误,所以我只是想知道它是否有任何漏洞?

谢谢,杰夫

最佳答案

我能想出的唯一解决方案是在需要使用 excel 功能时在线程上创建一个锁。这只是确保我一次只有一个进程使用 excel。它并不完美,尤其是当不相关的进程也尝试使用 excel 时,但这是我能想到的唯一修复方法。

关于c# Excel Interop 等待处理 0x800AC472 错误的替代方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411016/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com