简体   繁体   English

对象中的C#Thead-Safe集合

[英]C# Thead-Safe collection in Object

This is just example code to illustrate my question. 这只是示例代码来说明我的问题。

Assume I have the following class: 假设我有以下课程:

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);

    }



    }
}

Main: 主要:

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

    }

In my main method I am calling createBox.add(); 在我的主要方法中,我正在调用createBox.add();。 and passing the necessary arguments. 并传递必要的参数。 Do I have to worry about thread-safety when it comes to calling my add method? 调用add方法时,我是否需要担心线程安全性? I don't want to make the Box class static . 我不想使Box类成为静态类 If thread-safety is an issue how would I go about fixing my code? 如果线程安全是一个问题,我将如何修复我的代码?

Assuming the behaviour of ConcurrentDictionary.TryAdd meets your requirements, you're fine. 假设ConcurrentDictionary.TryAdd的行为满足您的要求,就可以了。 You'd be in an even better position if you made the boxItems field read-only. 如果将boxItems字段设置为只读,那么您的位置会更好。

It's worth reading the docs in detail when you use the concurrent collections, to see exactly what can happen. 值得在使用并发集合时详细阅读文档,以了解可能发生的情况。 For example, you may want AddOrUpdate instead of TryAdd - what you do want to happen if the key already exists in the dictionary? 例如,您可能希望AddOrUpdate代替TryAdd -你发生,如果关键在字典中已经存在呢?

Thread safety is not an issue in your case . Thread safety is not an issue in your case your box.add method is effectively adding to Concurrent dictionary which is thread safe. 您的box.add方法有效地添加到了并发字典中 ,这是线程安全的。 So you need not worry about thread safety. 因此,您不必担心线程安全性。

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

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