I'm currently processing xml messages with C#. It is working But I'm not confident that my code is fast enough. There are 3 possible messages I can receive. When I receive one the message an event is triggered and I can access the object outside of this thread and do the necessary processing. The method start is running in a separate thread.
public void Start()
{
NameTable nt = new NameTable();
object frameAck = nt.Add("frameack");
object alarmResponse = nt.Add("alarmresponse");
object watchdog = nt.Add("watchdog");
StreamReader sr = new StreamReader(_tcpClient.GetStream());
XmlReaderSettings settings = new XmlReaderSettings
{
NameTable = nt,
ConformanceLevel = ConformanceLevel.Fragment
};
XmlReader xr = XmlReader.Create(sr, settings);
while (!_requestStop)
{
try
{
while (xr.Read())
{
if (xr.NodeType == XmlNodeType.Element)
{
object localName = xr.LocalName; // Cache the local name to prevent multiple calls to the LocalName property.
if (watchdog == localName)
OnWatchdogComplete(new CustomEventArgs(xr.ToClassFromXmlStream<WatchdogFrame>()));
if (alarmResponse == localName)
OnAlarmResponseComplete(new CustomEventArgs(xr.ToClassFromXmlStream<AlarmResponse>()));
if (frameAck == localName)
OnAckComplete(new CustomEventArgs(xr.ToClassFromXmlStream<FrameAck>()));
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
xr.Close();
sr.Close();
Console.WriteLine("Stopping TcpXmlReader thread!");
}
This is my extensionmethod to deserialize to an object.
public static T ToClassFromXmlStream<T>(this XmlReader xmlStream)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(xmlStream);
}
When I close the program I always get the errors:
There is an error in XML document (9, 12).
Cannot access a disposed object.
Object name: 'System.Net.Sockets.NetworkStream'.
When I was string processing this it would seem that is was going a lot faster. But it was very complex and this very easy.
IDisposable
in there probably), it will be a very good fit on Code Review! :) \$\endgroup\$