winforms 持续运行BackgroundWorker

mjqavswn  于 2023-02-05  发布在  其他
关注(0)|答案(5)|浏览(175)

我需要能够连续运行我的BackgroundWorkerDoWork事件包含一个池线程进程,OnComplete更新我的UI。
我一直无法找到一种方法来无限循环BackgroundWorker.RunWorkerAsync()方法而不冻结整个程序。任何帮助将不胜感激。

bxfogqkk

bxfogqkk1#

你必须在你的DoWork方法中创建一个循环。要更新你的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");
        }        
    }
o75abkj4

o75abkj42#

我曾经在需要在后台运行的时候这样做过。如果你试图在backgroundworker运行的时候运行它,你会得到一个异常!这就是为什么我让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.
}
xmq68pz9

xmq68pz93#

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
        {

        }
    }
ukxgm1gy

ukxgm1gy4#

在backgroundworker已完成事件时,只需再次启动后台工作进程

fkaflof6

fkaflof65#

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

相关问题