从C#中的线程调用静态方法

时间:2013-05-21 19:25:46

标签: c# multithreading

我正在尝试使用this great project,但由于我需要扫描许多图像,因此这个过程需要花费很多时间才能进行多线程处理。 但是,由于对图像进行实际处理的类使用Static methods并且正在Objects操纵ref,所以我不确定如何正确处理。我从主线程中调用的方法是:

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 个答案:

答案 0 :(得分:1)

我很确定它是线程安全的。 有两个字段,它们是配置字段,在类中没有修改。 所以基本上这个类没有状态,所有计算都没有副作用 (除非我没有看到一些非常模糊的东西)。

此处不需要Ref修饰符,因为不会修改引用。

答案 1 :(得分: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");
    }
}