【问题标题】:How to use multiple threads of the same class in C#如何在C#中使用同一类的多个线程
【发布时间】:2012-09-28 09:16:02
【问题描述】:

我有一个包含一堆方法的类。例如

     private int forFunction(String exceptionFileList, FileInfo z, String compltetedFileList, String sourceDir)
        {
            atPDFNumber++;
            exceptionFileList = "";
            int blankImage = 1;
            int pagesMissing = 0;

            //delete the images currently in the folder
            deleteCreatedImages();
            //Get the amount of pages in the pdf
            int numberPDFPage = numberOfPagesPDF(z.FullName);

            //Convert the pdf to images on the users pc
            convertToImage(z.FullName);

            //Check the images for blank pages
            blankImage = testPixels(@"C:\temp", z.FullName);

            //Check if the conversion couldnt convert a page because of an error
            pagesMissing = numberPDFPage - numberOfFiles;
}

现在我现在尝试的是在一个线程中访问该类.. 但不仅仅是一个线程,也许大约 5 个线程来加速处理,因为一个有点慢。

现在在我看来,那将是一片混乱……我的意思是一个线程更改变量,而另一个线程忙于它们等等等等,并在所有这些方法中锁定每个变量……不会玩得开心...

所以我提出什么建议,不知道它是否正确..是这样的

  public void MyProc()
    {
      if (this method is open, 4 other threads must wait)
    {
      mymethod(var,var);
    }
     if (this method is open, 4 other threads must wait and done with first method)
    {
      mymethod2();
    }
  if (this method is open, 4 other threads must wait and done with first and second method)
       {
          mymethod3();
    }
         if (this method is open, 4 other threads must wait and done with first and second and third method)
        {
          mymethod4();
        }
    }

这是否是解决多个线程同时访问多个方法的问题的正确方法?

这些线程只会访问该类 5 次,不会更多,因为工作负载将被平均分配。

【问题讨论】:

  • 你的术语混用真的没有帮助。你不运行一个类,调用myClass 的方法也不常见。如果你能举一个更具体的例子会有所帮助......
  • 如果您针对的是特定语言,请将其作为标签添加到您的问题中。现在我添加了“java”标签,因为代码看起来像 Java。
  • 啊该死的我完全忘记了!谢谢

标签: c# multithreading class methods


【解决方案1】:

是的,这是您的选择之一。但是,您拥有的条件表达式应该使用 lock 语句替换,或者更好的是,使方法同步:

[MethodImpl(MethodImplOptions.Synchronized)]
private int forFunction(String exceptionFileList, FileInfo z, String compltetedFileList, String sourceDir)

这并不是真正的条件,因为这里没有任何条件。下一个到来的线程必须等待,然后它必须继续。它实际上是在不执行任何指令的情况下休眠,然后从外部唤醒。

还请注意,当您担心在非同步方法的并行执行期间变量混乱时,这只适用于成员变量(类字段)。它不适用于在方法中声明的局部变量,因为每个线程都有自己的副本。

【讨论】:

  • @Ruan Me too.Since your tag is c# but the example in answer is in java (虽然差异很小)。
  • @Ruan - 感谢您的回复,我已手动应用您的编辑。我想我最初在这里看到了一个 Java 错误标记。
  • @Jirka - 没问题。我认为有,Joachim 补充说它认为它是 java,因为我一开始没有指定 c#。谢谢吉尔卡。
猜你喜欢
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-14
  • 2018-07-03
  • 2013-06-01
相关资源
最近更新 更多