我正在编写一个应用程序,我在其中运行了一个进程BackgroundWorker.我想支持从用户界面取消,但我没有看到一个简单的方法来做到这一点.
该Process实际上是一个相当长的运行命令行exe文件.输出通过Progress.OutputDataReceived事件异步重定向,并用于向GUI报告进度.
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
using (var process = new Process())
{
//...
process.Start()
//...
process.WaitForExit();
}
}
private void CancelWorker()
{
worker.CancelAsync();
// where to actually listen for the cancellation???
}
Run Code Online (Sandbox Code Playgroud)
除了StandardInput应用程序本身将响应特定输入以中止之外,似乎没有办法让进程"监听"来自主线程的任何输入.
有没有办法根据主线程的取消请求取消进程?
出于我在运行过程中运行的EXE的目的,我可以调用Process.Close()退出而没有任何副作用,但该Process对象仅为worker_DoWork()方法所知,因此我需要跟踪Process实例以进行取消. ..这就是为什么我希望有更好的方法.
(如果重要的话,我的目标是.NET 3.5以解决兼容性问题.)
对于协作取消,您需要监听BackgroundWorker.DoWork事件 中的BackgroundWorker.CancellationPending 。
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
using (var process = new Process())
{
//...
process.Start()
//...
while(true)
{
if ((sender as BackgroundWorker).CancellationPending && !process.HasExited)
{
process.Kill();
break;
}
Thread.Sleep(100);
}
process.WaitForExit();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1602 次 |
| 最近记录: |