开发者

proper way to iterate through data in a class when the data changes asynchronously

I have a C# class which has a dictionary inside it. The class listens asynchronously to messages that, upon arrival and processing, alter the data in the dictionary.

What is the "correct" way for an app that uses an instance of this class to iterate through the data in the dictionary? Do I have to wrap it into another class and implement some sort of enumerator? Is it appropriate to add something like Pause a开发者_JAVA技巧nd Resume methods to the class that the app can call when it wants to iterate over the data?


Well, you should lock on the dictionary any time you are iterating over it or modifying it.

Like so:

var d = new Dictionary<int, string>();

lock (d)
{
    d.Add(1, "Q");
}

lock (d)
{
    foreach (var p in d)
    {
        Console.WriteLine(p.Key + " => " + p.Value);
    }
}

If your iteration is going to do something substantial, you should copy before iterating.

IList<KeyValuePair<int, string>> d2;

lock (d)
{
    d2 = d.ToList();
}

foreach (var p in d2)
{
    Console.WriteLine(p.Key + " => " + p.Value);
}


Another option is the copy the data before iterating.


There are really 2 options for how the client can iterate over the data

  1. It can acquire the same synchronization lock that is used to protect the data when being updated asnchrously.
  2. The class in charge of the data can return an independent copy of the data to the caller
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜