このコードを例として使用しています。次のPersonクラスがあるとします。これはC#でConcurrentdictionaryを反復処理する適切な方法ですか?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace dictionaryDisplay
{
class Person
{
public string FirstName { get; private set;}
public string LastName { get; private set; }
public Person(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
public override string ToString()
{
return this.FirstName + " " + this.LastName;
}
}
}
メインプログラム
static void Main(string[] args)
{
ConcurrentDictionary<int, Person> personColl = new ConcurrentDictionary<int, Person>();
personColl.TryAdd(0, new Person("Dave","Howells"));
personColl.TryAdd(1, new Person("Jastinder","Toor"));
Person outPerson = null;
personColl.TryRemove(0, out outPerson);
//Is this safe to do?
foreach (var display in personColl)
{
Console.WriteLine(display.Value);
}
}
これは、同時辞書を反復処理の安全な方法は何ですか?そうでない場合、それを行うための安全な方法は何ですか?
辞書からPersonオブジェクトを削除したいとします。私はtryRemoveメソッドを使用しますが、outPersonオブジェクトで何をしますか?削除されたPersonが辞書に格納されます。 outPersonオブジェクトで完全にクリアするにはどうすればよいですか?
ニットを選択しようとしていませんが、使用するステートメントがありません: 'using System.Collections.Concurrent;'? –
それはそこにあり、ちょうどそれを含んでいませんでした。 –