[英]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.