嵌套的Parallel.ForEach调用是否存在任何线程安全问题?

时间:2018-02-22 16:20:31

标签: c# thread-safety static-methods

如果我要将列表传递给使用Parallel.ForEach并更新列表中对象的静态方法,是否有任何线程安全问题。

class Program
{
    static void Main(string[] args)
    {
        List<Fruit> fruitList = new List<Fruit>();
        fruitList.Add(new Fruit() { Name = "Apple", Active = false });
        fruitList.Add(new Fruit() { Name = "Orange", Active = false });
        fruitList.Add(new Fruit() { Name = "Strawberry", Active = false });

        Fruit.ApplyUpdate(fruitList);            
    }
}

public class Fruit
{
    public string Name { get; set; }
    public bool Active { get; set; }
    public List<FruitSupplier> Suppliers { get; set; }

    public Fruit()
    {
        this.Suppliers = new List<FruitSupplier>();
    }

    public static void ApplyUpdate(List<Fruit> fruitList)
    {
        Parallel.ForEach(fruitList, fruit =>
        {
            //do some processing and set the active property for example
            if (fruit.Name != "Apple")
                fruit.Active = true;

            Parallel.ForEach(fruit.Suppliers, fruitSupplier =>
            { 
                //do some processing for the suppliers
                fruitSupplier.Name = "Fruits R Us";
            });
        });
    }
}

public class FruitSupplier
{
    public string Name {get;set;}
    public string Country {get;set;}
}

我已编辑该示例以包含嵌套的Parallel.ForEach。如果我们将此程序Main()视为Web服务,则传递给ApplyUpdate()方法的实际listg将不会被除两个Parallel.ForEach之外的任何其他代码修改。

0 个答案:

没有答案