17

我需要能够持续运行我的BackgroundWorker. 该DoWork事件包含一个池线程进程和OnComplete更新我的 UI。

我一直无法找到一种方法来无限循环该BackgroundWorker.RunWorkerAsync()方法而不会冻结整个程序。任何帮助将不胜感激。

4

4 回答 4

28

您必须在 DoWork-Method 中创建一个循环。要更新您的 UI,您应该使用 ProgressChanged 方法。这是一个小例子

 public Test()
    {
        this.InitializeComponent();
        BackgroundWorker backgroundWorker = new BackgroundWorker
            {
                 WorkerReportsProgress = true,
                WorkerSupportsCancellation = true
            };
        backgroundWorker.DoWork += BackgroundWorkerOnDoWork;
        backgroundWorker.ProgressChanged += BackgroundWorkerOnProgressChanged;
    }

    private void BackgroundWorkerOnProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        object userObject = e.UserState;
        int percentage = e.ProgressPercentage;
    }

    private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = (BackgroundWorker) sender;
        while (!worker.CancellationPending)
        {
            //Do your stuff here
            worker.ReportProgress(0, "AN OBJECT TO PASS TO THE UI-THREAD");
        }        
    }
于 2013-11-04T14:19:03.413 回答
8

过去,当需要在后台运行某些东西时,我已经这样做了。如果你在后台运行时尝试运行它,你会得到一个异常!这就是为什么我让 BackGroundWorker 在完成事件中完成时自行启动。

然后它将永远循环。

private void Main_Load(object sender, EventArgs e)
{
   // Start Background Worker on load
   bgWorker.RunWorkerAsync();
}

private void bgWorker_DoWork(object sender, DoWorkEventArgs e)
{
   Thread.Sleep(1000);   // If you need to make a pause between runs
   // Do work here
}

private void bgCheck_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// Update UI

// Run again
bgWorker.RunWorkerAsync();   // This will make the BgWorker run again, and never runs before it is completed.
}
于 2013-12-01T18:33:39.860 回答
0
 timer.interval=60000 // 1 min

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        timer1.Start();

    }
 private void timer1_Tick(object sender, EventArgs e)
    {
        try
        {
           //Do something
        }
        catch
        {


        }
    }
于 2016-08-09T17:04:17.217 回答
-2

如果您的程序冻结,可能是因为您无限循环的后台工作线程正在旋转,使用 100% 的 CPU。您还没有说明为什么需要它在无限循环中运行,但是您可以从将 aThread.Sleep放入该循环开始。

于 2013-11-04T14:46:53.380 回答