BackgroundWorker DoWork delegate fails when using XmlReader
I'm trying to read an XML stream using BackgroundWorker
:
private void backgroun开发者_JAVA技巧dWorker1_DoWork(object sender, DoWorkEventArgs e)
{
NetworkStream serverStream = clientSocket.GetStream();
XmlReader r = XmlReader.Create(serverStream);
while (r.Read())
{
output something using backgroundWorker1.ReportProgress object
}
}
I call this using backgroundWorker1.RunWorkerAsync(null)
in a button click event.
The program compiles and runs fine but the process stalls at XmlReader.Create
. No errors, but it says that it can not evaluate expression because a native frame is on top of the call stack. So, it's probably waiting for the process to finish.
The problem is that if I do this directly from the mouse click without using the backgroundWorker object, the program runs just fine.
Any ideas? Thanks.
The documentation states that XmlReader.Create
reads the first few bytes to determine the encoding.
I think the problem is, that your stream doesn't return any data. This might be the case because another thread already read all the data.
It sounds like the XML reader creation is getting blocked on reading the stream.
There might be a deadlock situation whereby the server stream will not send bytes until the background worker thread has performed some task (seems unlikely however)
As @Daniel Hilgarth suggests, perhaps another thread has fully read the stream previously?
There could also be some synchronisation issues here. Try adding a lock statement around the code, e.g.:-
private readonly object streamLocker = new object();
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
lock(streamLocker)
{
NetworkStream serverStream = clientSocket.GetStream();
XmlReader r = XmlReader.Create(serverStream);
while (r.Read())
{
// output something using backgroundWorker1.ReportProgress object
}
}
}
精彩评论