如何实现停止/取消按钮

本文关键字:取消 按钮 何实现 实现 | 更新日期: 2023-09-27 18:08:49

我有一个processData()方法,它接受大量数据并对其进行一些处理。有一个启动处理的开始按钮。我需要一个取消按钮,可以在任何地方停止处理。我该如何实现呢?我不明白的是,一旦处理开始,如何使取消按钮可用,因为当函数运行时,UI的其余部分被冻结。

如何实现停止/取消按钮

BackgroundWorker。CancelAsync方法就是你需要的。这是一个很好的例子。

如果你有一个耗时的进程,你将不得不使用一个单独的线程来处理它,以支持取消。如果你在主线程(UI线程)中执行那个耗时的进程,它将会很忙,直到它完成那个任务才会考虑你的取消请求。这就是为什么你会遇到UI冻结。

如果你使用backgroundWorker来完成耗时的任务,如果你在backgroundWorker中检查了CancellationPending标志。DoWork方法可以实现你想要的。

using System;  
using System.Collections.Generic;  
using System.ComponentModel;  
using System.Data;  
using System.Drawing;  
using System.Text;  
using System.Windows.Forms;  
namespace BackgroundWorker  
{  
    public partial class Form1 : Form  
    {  
        public Form1()  
        {  
            InitializeComponent();  
            //mandatory. Otherwise will throw an exception when calling ReportProgress method  
            backgroundWorker1.WorkerReportsProgress = true;   
            //mandatory. Otherwise we would get an InvalidOperationException when trying to cancel the operation  
            backgroundWorker1.WorkerSupportsCancellation = true;  
        }  
        //This method is executed in a separate thread created by the background worker.  
        //so don't try to access any UI controls here!! (unless you use a delegate to do it)  
        //this attribute will prevent the debugger to stop here if any exception is raised.  
        //[System.Diagnostics.DebuggerNonUserCodeAttribute()]  
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)  
        {  
            //NOTE: we shouldn't use a try catch block here (unless you rethrow the exception)  
            //the backgroundworker will be able to detect any exception on this code.  
            //if any exception is produced, it will be available to you on   
            //the RunWorkerCompletedEventArgs object, method backgroundWorker1_RunWorkerCompleted  
            //try  
            //{  
                DateTime start = DateTime.Now;  
                e.Result = "";  
                for (int i = 0; i < 100; i++)  
                {  
                    System.Threading.Thread.Sleep(50); //do some intense task here.  
                    backgroundWorker1.ReportProgress(i, DateTime.Now); //notify progress to main thread. We also pass time information in UserState to cover this property in the example.  
                    //Error handling: uncomment this code if you want to test how an exception is handled by the background worker.  
                    //also uncomment the mentioned attribute above to it doesn't stop in the debugger.  
                    //if (i == 34)  
                    //    throw new Exception("something wrong here!!");  
                    //if cancellation is pending, cancel work.  
                    if (backgroundWorker1.CancellationPending)  
                    {  
                        e.Cancel = true;   
                        return;  
                    }  
                }  
                TimeSpan duration = DateTime.Now - start;  
                //we could return some useful information here, like calculation output, number of items affected, etc.. to the main thread.  
                e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";  
            //}  
            //catch(Exception ex){  
            //    MessageBox.Show("Don't use try catch here, let the backgroundworker handle it for you!");  
            //}  
        }  
        //This event is raised on the main thread.  
        //It is safe to access UI controls here.  
        private void backgroundWorker1_ProgressChanged(object sender,   
            ProgressChangedEventArgs e)  
        {  
            progressBar1.Value = e.ProgressPercentage; //update progress bar  
            DateTime time = Convert.ToDateTime(e.UserState); //get additional information about progress  
            //in this example, we log that optional additional info to textbox  
            txtOutput.AppendText(time.ToLongTimeString());  
            txtOutput.AppendText(Environment.NewLine);              
        }  
        //This is executed after the task is complete whatever the task has completed: a) sucessfully, b) with error c)has been cancelled  
        private void backgroundWorker1_RunWorkerCompleted(object sender,   
            RunWorkerCompletedEventArgs e)  
        {  
            if (e.Cancelled) {  
                MessageBox.Show("The task has been cancelled");  
            }  
            else if (e.Error != null)  
            {                  
                MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());  
            }  
            else {  
                MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());  
            }  
        }  
        private void btoCancel_Click(object sender, EventArgs e)  
        {  
            //notify background worker we want to cancel the operation.  
            //this code doesn't actually cancel or kill the thread that is executing the job.  
            backgroundWorker1.CancelAsync();  
        }  
        private void btoStart_Click(object sender, EventArgs e)  
        {  
            backgroundWorker1.RunWorkerAsync();  
        }  
    }  
}  

使用BackgroundWorker

将重代码放在DoWork事件中

取消按钮应调用BackgroundWorker上的CancelAsync

DoWork中的健康代码中,定期检查CancellationPending属性。如果属性为true,则应中止该工作。

处停止处理

如果你的意思是进程应该立即停止,而不是等待它检查取消令牌的时刻,你可以考虑在一个单独的AppDomain中运行进程,并在取消时杀死它。

虽然这是完全可能的,但我建议像其他答案一样控制终止,特别是当您的流程改变外部状态时。