用于创建Word文档的线程同步

问题描述

我有一个Word模板文件,在其中我用数据替换了某些标签。 我尝试使用Parallel同步文件创建,但是正如您在图片上看到的那样,过一会儿我得到了该文件的使用窗口。 我在互联网上进行了查询,这是因为单词文件没有关闭,因为它被声明为全局文件,但是该解决方案(Wordapp not closing in Thread or Parallel process)与我的代码有很大不同,我无法理解我需要去做。我是创建Word文件的初学者,所以我不太了解我的代码

有人可以给我潜在的解决方案吗?

enter image description here

单词创建者:

private static void CreateWordDocument(object filename,object SaveAs,string title,string description,string price)
        {
            
            Word.Application wordApp = new Word.Application();
            object missing = Missing.Value;
            Word.Document myWordDoc = null;

            if (File.Exists((string)filename))
            {
                object readOnly = false;
                object isVisible = false;
                wordApp.Visible = false;
                
                myWordDoc = wordApp.Documents.Open(ref filename,ref missing,ref readOnly,ref missing);
               
                
                myWordDoc.Activate();

                //find and replace
                ReplaceTextInWordDoc(wordApp,"<title>",title);
                ReplaceTextInWordDoc(wordApp,"<description>",description);
                ReplaceTextInWordDoc(wordApp,"<price>",price);

            }
            else
            {
                Console.WriteLine("File not Found!");
            }

            //Save as
            myWordDoc.SaveAs2(ref SaveAs,ref missing);

            myWordDoc.Close();
            wordApp.Quit();
            Console.WriteLine("File Created!");
        }

使用Parallel调用我的方法

Parallel.ForEach(gameList,(game) =>
            {
                string path = "C:\\Users\\Bence\\Desktop\\ps2\\" + game.title;
                Directory.CreateDirectory(path);
               
                    CreateWordDocument(@"C:\Users\Bence\Desktop\myWord\temp.docx",path + "\\" + game.title + ".docx",game.title,description,game.price);
                
                
            });

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)