I’m working on a C# application where I need to process multiple Word documents in parallel. Specifically, I’m trying to apply a bookmark conversion method to each document concurrently. Here’s the signature of the method I’m working with:

ConvertBookMark(string introText, ConvertionNode convertionNode1, Application wordApp1, Document doc1, string docFilePath, string solnPath, string clientName, string ssoConfigModel);

To achieve parallel execution, I’m using Task.Run() but it seems like the tasks aren’t running in parallel as expected. Below is a snippet of my code where I’m trying to queue each document processing task:

List<WordTaskInfo> wordTaskInfos = new List<WordTaskInfo>();
List<Task> tasks = new List<Task>();

foreach (var item in someCollection) // Assume someCollection is defined elsewhere
{
    wordTaskInfos.Add(new WordTaskInfo
    {
        DocFilePath = item.DocfilePath,
        BookmarkName = item.BookmarkName,
        // Other properties initialization
    });

    tasks.Add(Task.Run(() =>
    {
        Log.LogBookmark($"Creating Instance Start :{item.BookmarkName}", DateTime.Now.ToString("HH:mm:ss"));
        lock (wordLock) // Assume wordLock is defined elsewhere
        {
            try
            {
                var wordApp = new Microsoft.Office.Interop.Word.Application();
                var doc = wordApp.Documents.Open(ref item.DocfilePath, // Other parameters omitted for brevity
                );
                
                ConvertBookMark(item.IntroText, item.ConvertionNode1, wordApp, doc, item.DocFilePath, item.SolnPath, item.ClientName, item.SsoConfigModel);
                
                doc.SaveAs2(item.DocFilePath, WdSaveFormat.wdFormatDocumentDefault, false);
                doc.Close();
                wordApp.Quit();
            }
            finally
            {
                // Cleanup logic here
            }
            Log.LogBookmark($"Creating Instance End :{item.BookmarkName}", DateTime.Now.ToString("HH:mm:ss"));
        }
    }));
}

Task.WaitAll(tasks.ToArray());

I’m wondering if I’m using Task.Run() correctly for parallel execution, or if there’s a better approach for handling parallelism in this scenario, especially considering the use of COM objects with Microsoft Office Interop. Any insights or suggestions would be greatly appreciated!

Khám phá các thẻ bài đăng