Recently, due to the chat scheduling service, this is the case. On the cluster Chat Server, each service sends UDP packets to the scheduling server at a certain frequency through socket, the scheduling server receives data packets from various chat servers, analyzes the corresponding data, and finally determines the currently idle Chat Server for chat users to quickly connect to the optimal server in real time, I want to use the dictionary data structure to cache the collected server summary data. during the development process, I encountered several difficult problems:
1. The collected data is implemented through multiple threads, which causes the dictionary thread security problems.
To address the problem of dictionary thread security, I inherited idictionary and re-constructed the thread security dictionary object. In fact, there is nothing complicated here, but it is added to the internal element of dictionary, add a lock to the deletion or deletion process.
2. This thread security problem is solved, but another problem occurs. I want to perform related analysis on the data in the dictionary. I want to copy a dictionary data in real time, take it for correlation analysis, so that the problem of deep copy of dictionary occurs. After verification, create another dictionary object and traverse the original dictionay structure and data for assignment. net reflection mechanism implements the copy operation, but the performance is poor. Another solution is to complete the deep copy of Data Objects through serialization and deserialization. This method is fast and efficient, therefore, this method is used. Here, only the second method is provided:
Public class threadsafedictionary <tkey, tvalue>: idictionary <tkey, tvalue>, icloneable
{
Public object clone ()
{
Binaryformatter formatter = new binaryformatter (null, new streamingcontext (streamingcontextstates. Clone ));
Memorystream stream = new memorystream ();
Formatter. serialize (stream, this );
Stream. Position = 0;
Object clonedobj = formatter. deserialize (Stream );
Stream. Close ();
Return clonedobj;
}
}
To implement deep copy, you only need this class to inherit the icloneable interface. By using the binaryformatter serializer, the object instance is first serialized and written into the memory stream. Then, the deserialization stream is deserialized and the deserialization object is returned,
This method is simple and efficient, and it is a good solution. Sometimes it is a different way of thinking, so it will have unexpected results.