csharp 使用后台工作程序执行后台任务

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 使用后台工作程序执行后台任务相关的知识,希望对你有一定的参考价值。

private BackgroundWorker bw = new BackgroundWorker();

public Page()
{
    InitializeComponent();

    bw.WorkerReportsProgress = true;
    bw.WorkerSupportsCancellation = true;
    bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
    bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}

private void buttonStart_Click(object sender, RoutedEventArgs e)
{
    if (bw.IsBusy != true)
    {
        bw.RunWorkerAsync();
    }
}

private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
    if (bw.WorkerSupportsCancellation == true)
    {
        bw.CancelAsync();
    }
}

private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    BackgroundWorker worker = sender as BackgroundWorker;

    for (int i = 1; (i <= 10); i++)
    {
        if ((worker.CancellationPending == true))
        {
            e.Cancel = true;
            break;
        }
        else
        {
            // Perform a time consuming operation and report progress.
            System.Threading.Thread.Sleep(500);
            worker.ReportProgress((i * 10));
        }
    }
}

private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if ((e.Cancelled == true))
    {
        this.tbProgress.Text = "Canceled!";
    }

    else if (!(e.Error == null))
    {
        this.tbProgress.Text = ("Error: " + e.Error.Message);
    }

    else
    {
        this.tbProgress.Text = "Done!";
    }
}

private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.tbProgress.Text = (e.ProgressPercentage.ToString() + "%");
}

以上是关于csharp 使用后台工作程序执行后台任务的主要内容,如果未能解决你的问题,请参考以下文章

如何在应用程序关闭时在颤动中执行后台任务?

从后台任务执行程序

如何在Android Studio中使用Java的应用程序后台执行HttpURLConnection之类的任务?

如何使用WorkManager执行后台任务(下)

执行后台任务的利器

[Abp 源码分析]后台作业与后台工作者