繁体   English   中英

对象中的C#Thead-Safe集合

[英]C# Thead-Safe collection in Object

这只是示例代码来说明我的问题。

假设我有以下课程:

enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;


namespace BoxesA4
{
class Box
{
    public double length { get; set; }
    public double width { get; set; }
    public double height { get; set; }

ConcurrentDictionary<int, string> boxItems = new ConcurrentDictionary<int, string>();


    public Box(double length,double width,double height)
    {
        this.length=length;
        this.width = width;
        this.height = height;

    }

    public double volume()
    {
        return this.length * this.width * this.height;
    }

    public void add(int index,string item)
    {
        boxItems.TryAdd(index, item);

    }



    }
}

主要:

    static void Main(string[] args)
    {
       Box createBox = new Box(10,10,5,5);
       createBox.add(0,"hammer");
       createBox.add(1,"saw");

    }

在我的主要方法中,我正在调用createBox.add();。 并传递必要的参数。 调用add方法时,我是否需要担心线程安全性? 我不想使Box类成为静态类 如果线程安全是一个问题,我将如何修复我的代码?

假设ConcurrentDictionary.TryAdd的行为满足您的要求,就可以了。 如果将boxItems字段设置为只读,那么您的位置会更好。

值得在使用并发集合时详细阅读文档,以了解可能发生的情况。 例如,您可能希望AddOrUpdate代替TryAdd -你发生,如果关键在字典中已经存在呢?

Thread safety is not an issue in your case 您的box.add方法有效地添加到了并发字典中 ,这是线程安全的。 因此,您不必担心线程安全性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM