C# 后台工作程序自定义取消消息
如何在后台工作人员的取消事件中显示自定义取消消息 我在DoWork事件中使用以下代码来取消工作人员C# 后台工作程序自定义取消消息,c#,backgroundworker,C#,Backgroundworker,如何在后台工作人员的取消事件中显示自定义取消消息 我在DoWork事件中使用以下代码来取消工作人员 string custom_cancel_msg="Cancelling BG WORKER due to some xxx reeasons"; if (bw.WorkerSupportsCancellation == true) { bw.CancelAsync(); } 我如何在已完成的活动中显示这一点。我只能访问以下内容 if ((e.Cancelled == true))
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!";
}
代码示例:
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();
}
}
public部分类BackgroundWorkerSample:Form
{
私人后台工作人员工作=null;
公共字符串CustomMessage{get;set;}
公共BackgroundWorkerSample()
{
初始化组件();
工作=新的后台工作人员();
work.workerSupportsScanCellation=true;
work.WorkerReportsProgress=true;
work.DoWork+=工人的工作;
work.ProgressChanged+=工人的进度已更改;
work.RunWorkerCompleted+=worker\u RunWorkerCompleted;
}
私有void worker\u RunWorkerCompleted(对象发送方,RunWorkerCompletedEventArgs e)
{
如果(如已取消)
{
lblStatus.ForeColor=颜色。红色;
lblStatus.Text=自定义消息;
}
其他的
{
lblStatus.ForeColor=颜色.绿色;
lblStatus.Text=$“结果为:{e.Result}”;
}
}
私有void worker\u ProgressChanged(对象发送方,ProgressChangedEventArgs e)
{
Text=$“计算结果…({e.ProgressPercentage}%)”;
}
私有void worker_DoWork(对象发送方,DoWorkEventArgs e)
{
对于(int i=0;i),如果您显示更多的上下文,这会有所帮助,但是您的代码是否都属于同一个类?在表单级别声明custom\u cancel\u msg
,而不是作为局部变量。