var worker = new BackgroundWorker()
{
WorkerReportsProgress = true,
WorkerSupportsCancellation = true,
};
var form = new Form();
var statusStrip = new StatusStrip();
var toolStripProgressBar = new ToolStripProgressBar()
{
Minimum = 0,
Maximum = 10,
};
statusStrip.Items.Add(toolStripProgressBar);
var cancelButton = new Button()
{
Location = new Point(110, 0),
Size = new Size(100, 50),
Text = "Cancel",
Enabled = false,
};
cancelButton.Click += (sender, e) =>
{
if (!worker.IsBusy) return;
cancelButton.Enabled = false;
worker.CancelAsync();
};
var button = new Button()
{
Size = new Size(100, 50),
Text = "Start",
};
button.Click += (sender, e) =>
{
if (worker.IsBusy) return;
button.Enabled = false;
cancelButton.Enabled = true;
worker.RunWorkerAsync(null);
};
form.Controls.Add(statusStrip);
form.Controls.Add(button);
form.Controls.Add(cancelButton);
form.Load += (x, y) =>
{
worker.DoWork += (sender, e) =>
{
// e.Result;
var args = e.Argument;
for (int i = 0; i < 10; i++)
{
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
worker.ReportProgress(i, null);
Thread.Sleep(1000);
if (i == 5)
{
throw new ApplicationException();
}
}
};
worker.RunWorkerCompleted += (sender, e) =>
{
toolStripProgressBar.Value = toolStripProgressBar.Minimum;
button.Enabled = true;
cancelButton.Enabled = false;
if (null != e.Error)
{
System.Windows.Forms.MessageBox.Show(form, e.Error.ToString(), e.Error.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (e.Cancelled)
{
MessageBox.Show(form, "処理はキャンセルされました。", "処理のキャンセル");
return;
}
// e.Result
// e.UserState
MessageBox.Show(form, "処理が終了しました。", "終了");
};
worker.ProgressChanged += (sender, e) =>
{
// var userState = e.UserState;
toolStripProgressBar.Value = e.ProgressPercentage;
};
};
Application.Run(form);
CQkJdmFyIHdvcmtlciA9IG5ldyBCYWNrZ3JvdW5kV29ya2VyKCkKCQkJewoJCQkJV29ya2VyUmVwb3J0c1Byb2dyZXNzID0gdHJ1ZSwKCQkJCVdvcmtlclN1cHBvcnRzQ2F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