【问题标题】:Eventhandler is fired more than once事件处理程序被多次触发
【发布时间】:2012-08-30 15:02:23
【问题描述】:

我的两个 EventHandler 有问题,它们的工作方式相同,所以这里有一个:

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowserWebsite.Url = new System.Uri(textBoxURL.Text, System.UriKind.Absolute);
        webBrowserWebsite.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserWebsite_DocumentCompleted);
    }


    void webBrowserWebsite_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
            StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\CurrentData.wfd");
            sw.Write(webBrowserWebsite.Document.Body.InnerText);
            sw.Close();
    }

问题是,EventHandler 多次触发,它不会停止! 为什么要这样做? 提前致谢

【问题讨论】:

  • 您能检查一下您的代码吗?这不会编译。

标签: events event-handling browser


【解决方案1】:

您编写的代码不会编译(您的 EventHandler 中的 StreamWriter 没有分配给任何东西)并且没有更多关于您如何调用它的上下文,很难确定。

但最可能的原因是您多次调用Form1_Load,但使用相同的webBrowserWebsite 对象。每次加载表单时,您都会添加一个新的事件处理程序。而且由于您没有显示任何代码来显示您删除事件处理程序的位置,我猜它会在您每次调用 Form_Load 时触发一次。

根据您的设计,您最好在构造函数中添加事件处理程序,这样无论您加载表单的次数如何,它都只会添加一次。

public Form1()
{
    webBrowserWebsite.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowserWebsite_DocumentCompleted);
}

private void Form1_Load(object sender, EventArgs e)
{
    webBrowserWebsite.Url = new System.Uri(textBoxURL.Text, System.UriKind.Absolute);
}

或者在事件处理器中移除事件处理器:

void webBrowserWebsite_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\CurrentData.wfd");
    sw.Write(webBrowserWebsite.Document.Body.InnerText);
    sw.Close();
    webBrowserWebsite.DocumentCompleted -= webBrowserWebsite_DocumentCompleted;
}

另外,由于StreamWriter 实现了IDisposible,您应该将它放在using 块内,或者至少在方法末尾调用sw.Dispose()

【讨论】:

  • 非常感谢,我已经删除了 Eventhandler 本身的开头,现在它可以完美运行了!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-13
  • 2016-07-26
  • 1970-01-01
  • 2019-02-27
  • 2013-07-06
  • 2018-09-22
相关资源
最近更新 更多