下面的代码通常可以工作,并且在将 docx/doc 保存到 pdf 后打开和关闭 word,但是当在线程或并行 for 循环中使用以下代码时,它不会,有任何想法吗?我已经提供了下面的所有代码。
这是在函数中使用时工作正常的代码。
wordApp = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document wordDocument = wordApp.Documents.Open(sourceFile, false);
wordDocument.ExportAsFixedFormat(destFile, WdExportFormat.wdExportFormatPDF);
object saveOption = Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges;
object originalFormat = Microsoft.Office.Interop.Word.WdOriginalFormat.wdOriginalDocumentFormat;
object routeDocument = false;
if (wordDocument != null)
((_Document)wordDocument).Close(ref saveOption, ref originalFormat, ref routeDocument);
if (wordApp != null)
((_Application)wordApp).Quit(ref saveOption, ref originalFormat, ref routeDocument);
wordDocument = null;
wordApp = null;
下面是我尝试调用上面代码的 Parallel.For 代码:
Parallel.For(1, Int32.Parse(iNrOfThreads.Text), new ParallelOptions { MaxDegreeOfParallelism = Int32.Parse(iNrOfThreads.Text) }, i =>
{
fileName = fileNameLarge + i.ToString() + ".doc";
fileName2 = fileNameLarge + i.ToString() + ".pdf";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName2);
GeneratePDFWithProgressWithCreate(sourceFile, destFile);
});
下面是生成线程的 for 循环,我尝试调用上面的代码:
for (int i = 1; i <= Int32.Parse(iNrOfThreads.Text); i++)
{
//fileName2 = fileNameSmall + i.ToString() + ".docx";
fileName = fileNameLarge + i.ToString() + ".doc";
fileName2 = fileNameLarge + i.ToString() + ".pdf";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName2);
// To copy a file to another location and
// overwrite the destination file if it already exists.
//System.IO.File.Copy(sourceFile, destFile, true);
//Thread thread = new Thread(() => GeneratePDFWithProgress(sourceFile, destFile + ".pdf"));
Thread thread = new Thread(() => GeneratePDFWithProgressWithCreate(sourceFile, destFile));
thread.Name = "Thread" + i.ToString();
thread.IsBackground = true;
thread.SetApartmentState(ApartmentState.MTA);
thread.Start();
}