我正在执行邮件合并之后要关闭文件然后关闭单词应用程序。这是我执行邮件合并的地方
Application myWordApp = new Application();
Word.Document myWordDoc = new Word.Document();
myWordDoc = myWordApp.Documents.Add(ref fileDocTempl, ref oMissing, ref oTrue);
myWordApp.Visible = false;
Word.MailMerge wrdMailMerge = myWordDoc.MailMerge;
List<object> listTable = GetTableName();
const string cmdText = "Select * from [{0}]";
Object oQuery = string.Format(cmdText, listTable[0]);
wrdMailMerge.OpenDataSource(excelSource, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing,oMissing, oMissing, oMissing, oMissing, oMissing, oQuery);
myWordApp.MailMergeAfterRecordMerge += myWordApp_MailMergeAfterRecordMerge;
myWordDoc.MailMerge.Execute(ref oFalse);
这是我关闭文件的地方
object doNotSaveChanges = WdSaveOptions.wdDoNotSaveChanges;
myWordDoc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
myWordApp.Quit(ref doNotSaveChanges, ref oMissing, ref oMissing);
但是当我关闭myWordDoc时出现以下错误:
RPC_E_CALL_REJECTED COMexeption
只有当我进行大量邮件合并时才会发生这种情况,如果我尝试使用50,一切正常,如果我尝试使用2000,我会收到报告的错误。
答案 0 :(得分:1)
可能的解决方法是将块放在while循环中出现错误的位置,并继续循环直到动作实际完成。
var ready = false;
var liCount = 0;
var pDelayBetweenRetry = 500;
var amountOfRetries = 10;
while(!ready)
{
try
{
myWordDoc.Close(ref doNotSaveChanges, ref oMissing, ref oMissing);
ready = true;
}
catch (System.Runtime.InteropServices.COMException loE)
{
liCount++;
if ((uint)loE.ErrorCode == 0x80010001)
{
// RPC_E_CALL_REJECTED - sleep half sec then try again
System.Threading.Thread.Sleep(pDelayBetweenRetry);
}
}
finally
{
if(liCount == amountOfRetries)
{
ready = true;
//Write error to file or database so you can follow up it didn't worked out
//as planned
}
}
}
然后再说;这是一种解决方法,这也意味着代码可能仍然存在于循环中==&gt;继续抛出异常==&gt;我添加了一个Finally循环来捕捉这种情况。
一些链接等:
http://msdn.microsoft.com/en-us/library/ms228772.aspx; is there a better way to handle RPC_E_CALL_REJECTED exceptions when doing visual studio automation?;