如何在后台工作人员的取消活动中显示自定义取消消息
我在DoWork事件中使用以下代码来取消工作程序
string custom_cancel_msg="Cancelling BG WORKER due to some xxx reeasons";
if (bw.WorkerSupportsCancellation == true)
{
bw.CancelAsync();
}
我如何在完成的活动中展示这一点。我只能访问以下内容
if ((e.Cancelled == true))
{
lblMessage.Text = "Transaction Canceled in between!";
//HOW CA|N I ACCESS THE CUSTOM MESSA|GE HERE??????????????????
}
else if (!(e.Error == null))
{
lblMessage.Text = ("Error: " + e.Error.Message);
}
else
{
lblMessage.Text = "Done!";
}
答案 0 :(得分:1)
代码示例:
public partial class BackgroundWorkerSample : Form
{
private BackgroundWorker work = null;
public string CustomMessage { get; set; }
public BackgroundWorkerSample()
{
InitializeComponent();
work = new BackgroundWorker();
work.WorkerSupportsCancellation = true;
work.WorkerReportsProgress = true;
work.DoWork += worker_DoWork;
work.ProgressChanged += worker_ProgressChanged;
work.RunWorkerCompleted += worker_RunWorkerCompleted;
}
private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
lblStatus.ForeColor = Color.Red;
lblStatus.Text = CustomMessage;
}
else
{
lblStatus.ForeColor = Color.Green;
lblStatus.Text = $"Result is : {e.Result}";
}
}
private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
lblStatus.Text = $"Calculating result... ({ e.ProgressPercentage }%)";
}
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 0; i <= 100; i++)
{
if (work.CancellationPending == true)
{
e.Cancel = true;
return;
}
work.ReportProgress(i);
System.Threading.Thread.Sleep(250);
}
e.Result = 42;
}
private void btnStart_Click(object sender, EventArgs e)
{
work.RunWorkerAsync();
}
private void btnCancel_Click(object sender, EventArgs e)
{
CustomMessage = "Calculation cancelled by user";
work.CancelAsync();
}
}
如您所见,CustomMessage
被定义为类成员,而不是DoWork中的局部变量,因此它可以在表单中的任何位置使用。
请注意我对C#6内插字符串的使用; - )
干杯