【问题标题】:backgroundworker_progresschanged not doing anythingbackgroundworker_progresschanged 没有做任何事情
【发布时间】:2016-12-28 01:45:49
【问题描述】:

我有一个程序,我想在其中检查用户机器的现有内部 IP,然后在它连接到 VPN 后检查新的内部 IP。我通过后台工作人员检查用户的 IP 是否已更改。这是我的以下代码:

        var worker = new BackgroundWorker();
        worker.DoWork += new DoWorkEventHandler(worker_DoWork);
        worker.RunWorkerAsync();


        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (Connection.CheckForInternetConnection()) //Makes sure an internet connection is available
            {
                CurrentInternalIP = GetIPAddress(); //Regularly retrieve the current IP so we can compare against the old IP
                if (CurrentInternalIP != OldInternalIP) //Compare the current IP address with the old one
                {
                    MessageBox.Show("IP has changed");//Make sure the event is working correctly
                    break;
                }
            }
        }

        void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            lblStatus.Text = "Connected to VPN.";
        }

现在 worker_DoWork 事件正常工作。但是,一旦 worker_DoWork 事件中的 IP 发生更改,worker_ProgressChanged 事件就不会更改标签的文本。我最初有我的代码来更改我的 worker_DoWork 事件中的标签文本,但这给了我一个错误,因为我正在访问一个标签而不是它创建的 UI - 所以这是不可能的。感谢您的帮助。

【问题讨论】:

  • worker.ReportProgress(...) 您的代码正在执行“工作”,因此只有您才能知道进度以及何时报告。

标签: c# text label backgroundworker


【解决方案1】:

看看你的代码,你已经将worker的DoWork事件分配给了worker_DoWorkEventHandler,但是到目前为止你还没有分配ProgressChanged。为了引发此事件,您必须将 WorkerReportsProgress 设置为 true 以使其正常工作您必须分配 Progress 的 EeventHandler,这可以通过以下方式完成:

 worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
 worker.WorkerReportsProgress = true;

您可以调用以下方法来触发 Progress changed 事件:

worker.ReportProgress(intPercent);// intPercent is an integer denotes the percentage

【讨论】:

  • 啊,我一直在看错误的地方。感谢您的回答。但是,在尝试 ReportProgress 时出现以下错误:“此后台工作人员声明它不报告进度。”。
  • @Harry:在初始化的同时添加worker.WorkerReportsProgress = true;,查看更新
  • 感谢我的帮助。
猜你喜欢
  • 2012-09-07
  • 2016-10-02
  • 2013-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多