4

たくさんのメソッドを持つクラスがあります。たとえば

     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;
}

今私が試しているのは、スレッド内のそのクラスにアクセスすることです。ただし、1つは少し遅いので、1つのスレッドだけでなく、処理を高速化するために約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回しかアクセスせず、それ以上はアクセスしません。

4

1 に答える 1

5

はい、それはあなたのオプションの 1 つです。ただし、lockステートメントを使用して条件式を置き換えるか、メソッドを同期させる必要があります。

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

ここでは何も条件付きでないため、実際には条件付きではありません。次に来るスレッドは待機する必要があり、その後続行する必要があります。命令を実行せずに文字どおりスリープ状態になり、外部から起動されます。

また、非同期メソッドの並列実行中に変数が台無しになることが心配な場合、これはメンバー変数 (クラス フィールド) にのみ適用されます。各スレッドはそれらの独自のコピーを持つため、メソッド内で宣言されたローカル変数には適用されません。

于 2012-10-08T06:51:48.073 に答える