2013-05-21 76 views
0

我試圖使用this great project但由於我需要掃描許多映像,因此我需要花費很多時間來處理多線程。
但是,由於使圖像實際處理的類使用Static methods並且正在操作Objectsref我不確定如何正確執行此操作。我從我的主線程中調用方法是:從C#中的線程調用靜態方法

public static void ScanPage(ref System.Collections.ArrayList CodesRead, Bitmap bmp, int numscans, ScanDirection direction, BarcodeType types) 
{ 
    //added only the signature, actual class has over 1000 rows 
    //inside this function there are calls to other 
    //static functions that makes some image processing 
} 

我的問題是,如果它的安全使用,使用此功能是這樣的:

List<string> filePaths = new List<string>(); 
     Parallel.For(0, filePaths.Count, a => 
       { 
        ArrayList al = new ArrayList(); 
        BarcodeImaging.ScanPage(ref al, ...); 
       }); 

我已經花了幾個小時的調試,並大部分時間我得到的結果是正確的,但我確實遇到了幾個我現在無法重現的錯誤。

編輯
我粘貼類的代碼在這裏:http://pastebin.com/UeE6qBHx

+2

沒有分析方法本身沒人能告訴你它是否是線程安全的! – Yahia

+1

「偉大的項目」仍使用過時的ArrayList類,這讓我擔心它的線程安全性。 –

+0

如果它使用全局變量(或者變量沒有用作參數或函數內部),那麼它是一個否定的。 –

回答

0

有沒有辦法告訴除非你知道,如果它存儲在局部變量或字段的值(在靜態類,而不是方法)。

所有本地變量都將罰款和實例每次調用,但字段不會。

一個極壞的榜樣:

public static class TestClass 
{ 
    public static double Data; 
    public static string StringData = ""; 

    // Can, and will quite often, return wrong values. 
    // for example returning the result of f(8) instead of f(5) 
    // if Data is changed before StringData is calculated. 
    public static string ChangeStaticVariables(int x) 
    { 
     Data = Math.Sqrt(x) + Math.Sqrt(x); 
     StringData = Data.ToString("0.000"); 
     return StringData; 
    } 

    // Won't return the wrong values, as the variables 
    // can't be changed by other threads. 
    public static string NonStaticVariables(int x) 
    { 
     var tData = Math.Sqrt(x) + Math.Sqrt(x); 
     return Data.ToString("0.000"); 
    } 
} 
1

我敢肯定它是線程安全的。 有兩個字段,它們是配置字段,不在類內部修改。 所以基本上這個類沒有狀態,所有的計算都沒有副作用 (除非我沒有看到非常模糊的東西)。

這裏不需要參考修飾符,因爲參考沒有修改。