【问题标题】:WebClient.OpenRead exception: "Value cannot be null."WebClient.OpenRead 异常:“值不能为空。”
【发布时间】:2010-09-23 13:26:59
【问题描述】:

我正在开发一种抓取器,它可以抓取一个网页的链接,然后创建执行线程 子页面的抓取。

这是线程的作用:

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:line 96 中的 MyAppName.Scraper.Scrape() 处的 System.Net.WebClient.OpenRead(String address)

您对解决此问题有什么建议吗? 提前谢谢你。

【问题讨论】:

  • 您是否在静态(模块/共享)类/方法中使用此代码?
  • 发布错误消息和堆栈跟踪将是一个好主意。既然是关于_Address,它是从哪里形成的?
  • @Oded 不,公共类的方法内的代码。
  • @Henk Holterman 确切的消息是“值不能为空。参数名称:地址”。例外是 System.ArgumentNullException。堆栈跟踪是:“在 MyAppFolder\Scraper.vb:line 96 中 MyAppName.Scraper.Scrape() 处的 System.Net.WebClient.OpenRead(String address)”
  • @Witchunter - 请编辑您的问题并在问题中添加堆栈跟踪和其他信息。在 cmets 中,它可能会被掩盖,而且肯定更难阅读。

标签: .net vb.net exception webclient


【解决方案1】:

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的位置。

【讨论】:

  • 我对你投了赞成票,因为这就是我要做的:检查空值并立即抛出异常或在逻辑要求时依赖默认值。只是为了将来的屈膝礼,请在发布之前转换为 VB.NET(无论转换什么),因为这被标记为“VB.NET”。谢谢。
猜你喜欢
  • 2020-03-01
  • 1970-01-01
  • 2021-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-19
  • 1970-01-01
相关资源
最近更新 更多