WebClient.OpenRead异常:“值不能为null。”

时间:2010-09-23 13:27:00

标签: .net vb.net exception webclient

我正在开发一个刮刀,用于抓取一个网页以获取链接,然后创建执行的线程 抓住子页面。

这是线程的作用:

Dim client As New WebClient()
Dim stream As Stream = client.OpenRead(_Address)
Dim streamReader As New StreamReader(stream, True)
_Content = streamReader.ReadToEnd()
streamReader.Close()
streamReader.Dispose()
stream.Close()
stream.Dispose()
client.Dispose()

我注意到有时候(通常当有更多的同时线程运行时)线程会抛出异常。它是随机发生的,异常在client.OpenRead处抛出,并显示"Value cannot be null. Parameter name: address"。我在这里也有一个try..catch,所以我在catch块中放了一个断点,看起来_Address当时有效,但代码抛出异常。

_Address是受保护的类字段,其他线程无法访问。

确切的信息是:

  

“值不能为空。参数名称:地址”。

例外是System.ArgumentNullException

堆栈跟踪是:

  在MyAppFolder \ Scraper.vb中的MyAppName.Scraper.Scrape()的System.Net.WebClient.OpenRead(字符串地址)

:第96行

您对修复此问题有什么建议吗? 提前谢谢。

1 个答案:

答案 0 :(得分:2)

WebClient.OpenRead(string address)的内部实施只是:

public Stream OpenRead(string address)
{
    if (address == null)
    {
        throw new ArgumentNullException("address");
    }
    return this.OpenRead(this.GetUri(address));
}

所以传递时_Address必须为null。

也许尝试这样的事情:

private string _address;
private string _Address
{
    get
    {
        if(_address == null)
            throw new ArgumentNullException("_Address was never set and is still null!");
        return _address;
    }
    set
    {
        if(value == null)
            throw new ArgumentNullException("_Address can not be null!");
        _address = value;
    }
}

所以基本上如果某些东西试图将_Address设置为null,当它发生时你会得到一个错误,并且可以在调用堆栈中看到它被设置为null。

相关问题