我試圖啓用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屬性的代碼?這些設置在哪裏? –