System. Collections. Generic. dictionary <,>
As long as the set is not modified,DictionaryYou can support multiple readers at the same time. Even so, enumerating a set from start to end is not a thread-safe process. When enumeration and write access compete for each other, the set must be locked throughout the enumeration process. To allow multiple threads to access a set for read/write operations, you must synchronize the data yourself. Today, the system. invalidopervationexcepti error is fixed when you use a dictionary generic class.On "The set has been modified, and enumeration operations may not be performed "". The original code is as follows:
Private void checkingtimeout ()
{
List <string> List = new list <string> ();
Lock (sessions)
{
Foreach (string sessionkey in sessions. Keys)
{
If (sessions [sessionkey]. istimeouted)
{
Logger. Info ("session [" + sessionkey + "] timeout ");
Unloadsession (sessionkey );
List. Add (sessionkey );
}
}
Foreach (string key in List)
{
Sessions. Remove (key );
}
}
}
Public void unloadsession (string sessionid)
{
Lock (sessions)
{
If (sessions. containskey (sessionid ))
{
DB. Delete (getsessionfromdatabase (sessionid ));
Dispatcher. unregisterallouteventsubscriber (sessionid );
Sessions. Remove (sessionid );
}
}
}
The error occurs because the set is modified during enumeration. The modified code is as follows:
Private void checkingtimeout ()
{
List <string> List = new list <string> ();
Lock (sessions)
{
Foreach (string sessionkey in sessions. Keys)
{
If (sessions [sessionkey]. istimeouted)
{
Logger. Info ("session [" + sessionkey + "] timeout ");
Unregistersession (sessionkey );
List. Add (sessionkey );
}
}
Foreach (string key in List)
{
Sessions. Remove (key );
}
}
}
Private void unregistersession (string sessionid)
{
Lock (sessions)
{
If (sessions. containskey (sessionid ))
{
DB. Delete (getsessionfromdatabase (sessionid ));
Dispatcher. unregisterallouteventsubscriber (sessionid );
}
}
}