简体   繁体   中英

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(); and passing the necessary arguments. Do I have to worry about thread-safety when it comes to calling my add method? I don't want to make the Box class static . 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. You'd be in an even better position if you made the boxItems field read-only.

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?

Thread safety is not an issue in your case . your box.add method is effectively adding to Concurrent dictionary which is thread safe. So you need not worry about thread safety.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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