【问题标题】:How to run parallel threads for multiple objects in a for loop如何在for循环中为多个对象运行并行线程
【发布时间】:2022-11-15 02:30:23
【问题描述】:

我有一个程序可以对图像中的选定文本进行 OCR。 When one line of text is selected the program takes about 20ms to give the result.但有时最多可以选择 5 行,因此时间乘以 5,结果大约需要 100ms。如何使用多线程并行处理行?我从来没有研究过多线程,所以我无法理解在线给出的解决方案。

我的代码如下:

     for (int i = 0; i < linecount; i++)
         {
           binaryimage.ROI = Rect[i];
           Bitmap bitmap2 = binaryimage.ToBitmap();
           doocr.trainingdatapath(@"./datapath", "eng");                          
           doocr.ProcessOCR(bitmap2, 1);                           
           string result = doocr.result().Replace(" ", "").Replace("  ", "");
         }      
                   

linecount(images) 可以是 1 到 5。如果有超过 1 个图像,我希望它们被并行处理。我怎样才能做到这一点?

【问题讨论】:

    标签: c# multithreading


    【解决方案1】:

    Parallel 类为此提供了一些解决方案。运行时将在后台处理所有事情:它将创建线程(或从线程池中使用它们),决定使用多少线程等等。请注意,您无法影响处理行的顺序。可能是第一行将完成,然后是第 4 行,然后是第 2 行,然后是第 3 行,然后是第 5 行。

    对于您的情况,应该使用相当于 for 循环的 For() 方法。我不知道您正在使用的库,因此我不知道它是否是线程安全的。可以肯定的是,循环的每次迭代都应该创建每个自己的变量(如果您在线程之间共享变量,如果您的方法不是线程安全的,您可能会遇到问题)。

    您可以将结果存储在ConcurrentBag 中,如果您完成了数据处理,您可以将其转换为列表。

    您的代码可能如下所示:

    var results = new ConcurrentBag<string>();
    Parallel.For(0, linecount - 1, i =>
    {
         var binaryimage = new BinaryImage();
         binaryimage.ROI = Rect[i];
         Bitmap bitmap2 = binaryimage.ToBitmap();
         var doocr = new Doocr();
         doocr.trainingdatapath(@"./datapath", "eng");                          
         doocr.ProcessOCR(bitmap2, 1);                           
         string result = doocr.result().Replace(" ", "").Replace("  ", "");
         results.Add(result);
    });
    var resultsList = new List<string>(results);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-09
      • 1970-01-01
      相关资源
      最近更新 更多