簡體   English   中英

后台工作人員自定義取消消息

[英]Background worker Custom cancel message

如何在后台工作人員的取消事件中顯示自定義取消消息

我在 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!";
        }

代碼示例:

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 中的局部變量,因此它可以在 Form 中的任何位置使用。

請注意我對 C# 6 內插字符串的使用;-)

干杯

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM