持续运行BackgroundWorker

时间:2013-11-04 14:13:24

标签: c# multithreading winforms backgroundworker infinite-loop

我需要能够连续运行BackgroundWorkerDoWork事件包含池线程进程,OnComplete更新我的UI。

在没有整个程序冻结的情况下,我无法找到无限循环BackgroundWorker.RunWorkerAsync()方法的方法。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:25)

您必须在DoWork-Method中进行循环。要更新UI,请使用ProgressChanged-Method。这是一个小例子,它的外观如何

 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");
        }        
    }

答案 1 :(得分:7)

过去我需要在后台运行时才这样做。 如果您在运行时尝试运行后台工作程序,您将获得一个重要的操作! 这就是为什么我在完成的事件中完成后使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.
}

答案 2 :(得分: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
        {


        }
    }

答案 3 :(得分:-2)

如果您的程序冻结,可能是因为您的无限循环后台工作线程正在旋转,使用100%CPU。你还没有说过为什么你需要它在一个无限循环中运行,但你可以先在那个循环中放一个Thread.Sleep