C#Excel interop – 如何测试互操作对象是否仍在工作并执行任务?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C#Excel interop – 如何测试互操作对象是否仍在工作并执行任务?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2224字,纯文字阅读大概需要4分钟。
内容图文
![C#Excel interop – 如何测试互操作对象是否仍在工作并执行任务?](/upload/InfoBanner/zyjiaocheng/803/51ac5b046abc44879cf5fd05c7695f9d.jpg)
我循环遍历几个Huncel excel文件的目录,并尝试一次刷新一个excel文件.我不断收到此错误,表示刷新操作仍在文件A上运行,例如,FileB正在尝试启动刷新操作.循环是快速的,不知怎的,我必须等待文件A上的先前刷新操作完成,然后才开始刷新文件B.
Unhandled Exception: System.Runtime.InteropServices.COMException: The
message filter indicated that the application is busy. (Exception from
HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER)) at
Microsoft.Office.Interop.Excel._Workbook.RefreshAll() at
RefreshExcelFiles.Program.RefreshFile(String fileName)
这是我的代码.在循环中开始处理新文件之前,如何等待刷新操作完成?或者,在开始新文件之前,等待wb对象上的编组释放操作完成?
using System;
using System.Configuration;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
namespace RefreshExcelFiles
{
internal class Program
{
private static string _fileDirectory;
private static Application _excelApp;
private static void Main(string[] args)
{
_fileDirectory = ConfigurationManager.AppSettings["FileDirectory"];
_excelApp = new Application();
_excelApp.DisplayAlerts = false;
Console.WriteLine("starting to refresh files");
int i = 0;
int total = Directory.GetFiles(_fileDirectory).Length;
foreach (string file in Directory.GetFiles(_fileDirectory))
{
i += 1;
Console.WriteLine("File " + file + " " + i.ToString() + "/" + total.ToString());
RefreshFile(file);
}
_excelApp.Quit();
Marshal.FinalReleaseComObject(_excelApp);
Console.WriteLine("press any key to exit");
Console.ReadLine();
}
private static void RefreshFile(string fileName)
{
_Workbook wb = _excelApp.Workbooks.Open(fileName, false);
wb.RefreshAll();
wb.Save();
wb.Close(Type.Missing, Type.Missing, Type.Missing);
Marshal.FinalReleaseComObject(wb);
}
}
}
解决方法:
我找到了问题的答案.我需要implement IMessageFilter RetryRejectedCall.对于使用IMessageFilter :: RetryRejectedCall,see this blog post的C#和VB.NET代码示例.
如果您没有自己注册MessageFilter(通过调用CoRegisterMessageFilter),您将获得默认行为,如果它将失败
被拒绝了. .Net将故障HRESULT转换为异常.为了解决当您尝试呼叫时服务器忙碌的可能性,您需要
在客户端代码中实现IMessageFilter :: RetryRejectedCall,并注册消息过滤器.在大多数情况下,您只需要等待
几秒钟,然后重试呼叫 – 通常这将是足够的时间使Word能够完成它正在做的任何事情,这样它就可以处理你的呼叫.
内容总结
以上是互联网集市为您收集整理的C#Excel interop – 如何测试互操作对象是否仍在工作并执行任务?全部内容,希望文章能够帮你解决C#Excel interop – 如何测试互操作对象是否仍在工作并执行任务?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。