我试图启用Kill
选项作为Process
与调用线程异步运行的情况。我的例子看起来像@ svick的回答here。我正试图在此post中实施@svick的建议。但是当我在UI中点击Kill
时,它看起来什么都不做(即,过程简单地像往常一样完成)。使用CancellationToken停止进程
根据@ TimCopenhaver的回应,这是预期的。但是如果我说出来了,它仍然没有做任何事情,这次是因为CancellationTokenSource
对象cts
为空,这是意外的,因为我在尝试杀死它之前在类的Dispatch
方法中实例化它。这里是我的代码片段:
UI
类:
private void OnKillCase(object sender, EventArgs args)
{
foreach (var case in Cases)
{
Args caseArgs = CaseAPI.GetCaseArguments(case);
CaseDispatcher dispatcher = CaseAPI.GetCaseDispatcher(case);
dispatcher.Kill();
CaseAPI.Dispose(caseArgs);
}
}
类:
private Task<bool> task;
private CancellationTokenSource cts;
public override bool IsRunning
{
get { return task != null && task.Status == TaskStatus.Running; }
}
public override void Kill()
{
//if (!IsRunning)
//{
// return;
//}
if (cts != null)
{
cts.Cancel();
}
}
public override async Task<bool> Dispatch()
{
cts = new CancellationTokenSource();
task = CaseAPI.Dispatch(Arguments, cts.Token);
return await task;
}
类:
public static async Task<bool> Dispatch(CaseArgs args, CancellationToken ctoken)
{
bool ok = true;
BatchEngine engine = new BatchEngine()
{
Spec = somespec,
CaseName = args.CaseName,
CaseDirectory = args.CaseDirectory
};
ok &= await engine.ExecuteAsync(ctoken);
return ok;
}
BatchEngine
类(这里是我调用CancellationToken
Register
方法,但不知道究竟在何处放置它,假设它事项):
public virtual Task<bool> ExecuteAsync(CancellationToken ctoken)
{
var tcs = new TaskCompletionSource<bool>();
string exe = Spec.GetExecutablePath();
string args = string.Format("--input={0} {1}", Input, ConfigFile);
try
{
var process = new Process
{
EnableRaisingEvents = true,
StartInfo =
{
UseShellExecute = false,
FileName = exe,
Arguments = args,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = CaseDirectory
}
};
ctoken.Register(() =>
{
process.Kill();
process.Dispose();
tcs.SetResult(false);
});
process.Exited += (sender, arguments) =>
{
if (process.ExitCode != 0)
{
string errorMessage = process.StandardError.ReadToEnd();
tcs.SetResult(false);
tcs.SetException(new InvalidOperationException("The batch process did not exit correctly. Error message: " + errorMessage));
}
else
{
File.WriteAllText(LogFile, process.StandardOutput.ReadToEnd());
tcs.SetResult(true);
}
process.Dispose();
};
process.Start();
}
catch (Exception e)
{
Logger.InfoOutputWindow(e.Message);
tcs.SetResult(false);
return tcs.Task;
}
return tcs.Task;
}
感谢您的关注和欣赏的任何想法。
'ctoken.Register'返回应该在'Exited'事件处理程序中处理的对象。 –
这应该基本上工作(除了一些竞争条件可能不会导致你的直接问题)。在cts.Cancel和process.Kill上放置断点,看看它出错的地方。平分。 – usr
您能否为CaseDispatcher显示您的IsRunning属性的代码?这些设置在哪里? –