[英]How to stop / destroy a running operation in c#
I have a windows form with a start and cancel button. 我有一个带有“开始”和“取消”按钮的Windows窗体。
The start button does the following: “开始”按钮执行以下操作:
bootLoader = new BootLoader(this, _form1);
bootloader.Start();
Now when the user clicks the start button, the BootLoader class writes data to the COM port. 现在,当用户单击开始按钮时,BootLoader类将数据写入COM端口。
What I want to know is that how can I stop this operation from completeing when the user clicks the cancel button. 我想知道的是,当用户单击“取消”按钮时,如何才能停止完成此操作。
Currently I just have the following: 目前,我只有以下内容:
this.Close();
But It just closes the form and the data carries on being written to the com port. 但是它只是关闭表格并且数据继续被写入到COM端口。
Use a cancellable BackgroundWorker ? 使用可取消的BackgroundWorker ?
var bw = new BackgroundWorkder();
bw.WorkerSupportsCancellation = true;
Then in your DoWork
worker function you'll need to monitor the CancellationPending
flag which will become true after you call bw.CancelAsync()
. 然后,在
DoWork
worker函数中,您需要监视CancellationPending
标志,该标志在调用bw.CancelAsync()
之后将变为true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.