ParallelFor 中的调用方法

Calling method in ParallelFor

我有一种方法 bool Method(Myobject Obj),我想在 ParallelFor() 循环中调用他。我真的可以这样做吗?这是线程安全的还是类似的?这样调用方法感觉有点不对劲

线程安全总是根据上下文或特定情况决定的。 比方说,你有这个:

public static bool Even(int i)
{
    return num % 2 == 0;  //true: even, false: odd
}

public static void ThreadSafe()
{
    bool[] arr = new bool[333];

    Parallel.For(0, arr.Length, index =>
    {
        arr[index] = Even(index);
    });
}

现在线程安全了吗?是的。 数组的每个索引都为 arr 中的一个相关索引赋值。 因此它可以并行完成。 但是现在呢?

   public static void ThreadUnsafe()
   {
       bool[] arr = new bool[333];

       Parallel.For(0, arr.Length, index =>
       {
           arr[index] = Even(index);
           int index2 = (index + 1) < arr.Length ? (index + 1) : index;
           arr[index2] = Even(index);
       });
    }

有了给定的索引,我们可以在 arr 中分配两个索引,其他线程也可以写入它。它不是线程安全的,不知道结果如何。

现在你可以看到,使用方法的上下文也可以决定它的线程安全性。

另外,线程安全有多种类型。