gpt4 book ai didi

c# - 持续运行 BackgroundWorker

转载 作者:可可西里 更新时间:2023-11-01 07:42:39 25 4
gpt4 key购买 nike

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

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

最佳答案

您必须在 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");
}
}

关于c# - 持续运行 BackgroundWorker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19769584/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com