gpt4 book ai didi

c# - ReportProgress 不使用 c# 中的任务调用 progressChanged

转载 作者:行者123 更新时间:2023-11-30 20:00:38 26 4
gpt4 key购买 nike

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int currentProgress=-1;

while (currentProgress<length)
{
currentProgress=Worker.progress;
backgroundWorker1.ReportProgress(currentProgress);
Thread.Sleep(500);
length = Worker.UrlList.Count;
}
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
int ix = e.ProgressPercentage;
progressBar1.Value = ix;
lblText.Text =ix+" %";
}

我编写了一个程序,通过读取一个包含大约 1000 个 URL 的文件来下载页面源代码。所以我使用任务来异步下载页面。这里的 Worker.progress 是当前执行的 URL 数量。尽管调试器点击了 backgroundWorker1.ReportProgress(currentProgress);,但它从未进入 backgroundWorker1_ProgressChanged

 private void StartButton_Click(object sender, EventArgs e)
{
t.makeUrlList(inputFile);

backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerAsync();
t.RunTasks();
Application.Exit();
}

后台 worker 在点击开始按钮时初始化...

这里是我创建任务的地方....

public void RunTasks()
{
if (numOfTasks > UrlList.Count)
numOfTasks=UrlList.Count-1;
Task[] t = new Task[numOfTasks];
int j = 0;
while ( j < UrlList.Count-1)
{

for (int i = 0; (i < t.Count())&&(j<UrlList.Count-1); i++)
{


try
{
if (t[i].IsCompleted || t[i].IsCanceled || t[i].IsFaulted)
{
t[i] = Task.Run(() => FindWIN(j));
j++;
progress = j;
}
}
catch (NullReferenceException ex)
{
t[i] = Task.Run(() => FindWIN(j));
j++;
progress = j;
}
}
}
}

最佳答案

如果想让BackgroundWorker支持更新进度信息,WorkerReportsProgress的值应该设置为true。如果此属性为 true ,则用户代码可以调用 ReportProgress 以启动事件 ProgressChanged 。

后台 worker 初始化:-

 backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork+=backgroundWorker1_DoWork;
backgroundWorker1.ProgressChanged+=backgroundWorker1_ProgressChanged;
backgroundWorker1.RunWorkerAsync();

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
int currentProgress = -1;

decimal length=1000;
while (currentProgress < length)
{
currentProgress = Worker.progress;
backgroundWorker1.ReportProgress(currentProgress);
Thread.Sleep(500);
length = Worker.UrlList.Count;
}
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) {
int ix = e.ProgressPercentage;
progressBar1.Value = ix;
lblText.Text = ix + " %";
}

关于c# - ReportProgress 不使用 c# 中的任务调用 progressChanged,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20560686/

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