我有一种名为 Sorter 的表单。其上有“jademy”按钮,可打开“进度窗口”窗口
private void jademy_Click(object sender, EventArgs e)
{
ProgressWindow progress = new ProgressWindow();
progress.ShowDialog();
}
“进度窗口”表格的代码如下:
public partial class ProgressWindow : Form
{
private BackgroundWorker backgroundWorker = new BackgroundWorker();
public ProgressWindow()
{
InitializeComponent();
stop.Visible = true;
ok.Visible = false;
backgroundWorker.RunWorkerAsync();
backgroundWorker.WorkerReportsProgress = true;
backgroundWorker.WorkerSupportsCancellation = true;
#region block1
backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
backgroundWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker_RunWorkerCompleted);
#endregion
}
private void stop_Click(object sender, EventArgs e)
{
backgroundWorker.CancelAsync();
}
private void ok_Click(object sender, EventArgs e)
{
this.Close();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1; i <= 100; i++)
{
Thread.Sleep(100);
backgroundWorker.ReportProgress(i);
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
this.Text = "Done: " + e.ProgressPercentage.ToString() + "%";
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if ((e.Cancelled == true))
{
MessageBox.Show("Cancelled", "Message", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
else if (!(e.Error == null))
{
MessageBox.Show("Error: " + e.Error.Message, "ERROR!", MessageBoxButtons.OKCancel);
}
else
{
ok.Visible = true;
stop.Visible = false;
}
}
}
现在。我有三个问题。
单击停止按钮不会执行任何操作。似乎“backgroundWorker.CancelAsync()”不会停止该过程。
When I close progress window and I want to run it again I have to wait some time before click on 'jademy' button. Otherwise progress window is displayed like this:
(and nothing changes) instead of this: It looks like the program "remembers" that work was done even though it is a new instance of ProgressWindow. Notice that on the incorrect version 'OK' button is visible at once - instead of waiting for the completion of the work.
我想澄清“块1”中的代码。说实话我并不完全理解。这部分真的重要吗?我的意思是,我找到了很多例子(也在这个论坛上 - 例如here https://stackoverflow.com/questions/12126889/how-to-use-winforms-progress-bar),其中未包含此部分,并且用户报告该解决方案有效。就我而言,如果没有这部分,进度条根本不起作用,但也许我做错了什么。
- 调用 CancelAsync 会停止任何挂起的工作。但如果工作已经开始,方法体需要检查是否调用了cancel。看取消异步 https://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.cancelasync%28v=vs.110%29.aspx
CancelAsync 提交终止挂起后台的请求
操作并将 CancellationPending 属性设置为 true。
当您调用 CancelAsync 时,您的工作方法有机会
停止其执行并退出。工作人员代码应定期检查 Cancellation Pending 属性查看它是否已设置为 true。
- 我对此一无所知。顺便说一句,图像不起作用。将其嵌入到问题中。
- 该代码分配一个在BackgroundWorker启动时执行的方法,并且您连接方法来报告进度并在后台工作完成后进行清理/更新。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)