简体   繁体   English

使用XmlReader时BackgroundWorker DoWork委托失败

[英]BackgroundWorker DoWork delegate fails when using XmlReader

I'm trying to read an XML stream using BackgroundWorker : 我正在尝试使用BackgroundWorker读取XML流:

    private void backgroundWorker1_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. 我在按钮单击事件中使用backgroundWorker1.RunWorkerAsync(null)进行调用。

The program compiles and runs fine but the process stalls at XmlReader.Create . 该程序可以编译并正常运行,但是该进程停在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. 问题是,如果我直接单击鼠标而不使用backgroundWorker对象,则程序运行正常。

Any ideas? 有任何想法吗? Thanks. 谢谢。

The documentation states that XmlReader.Create reads the first few bytes to determine the encoding. 该文档指出XmlReader.Create读取前几个字节以确定编码。
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. 听起来XML阅读器的创建在读取流时被阻止了。

  • 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? 正如@Daniel Hilgarth所建议的那样,也许另一个线程之前已经完全读取了流?

There could also be some synchronisation issues here. 这里也可能存在一些同步问题。 Try adding a lock statement around the code, eg:- 尝试在代码周围添加一个锁语句,例如:

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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM