我正在尝试为从Kill
调用线程异步运行的案例启用Process
选项。我的例子看起来像@ svick的回答here。我正试图在post中实施@svick的建议。但是当我点击用户界面中的Kill
时,它似乎什么都不做(即,过程只是像往常一样运行完成)。
根据@ TimCopenhaver的回应,这是预期的。但是如果我注释掉它,它仍然没有做任何事情,这次是因为CancellationTokenSource
对象cts
为空,这是意料之外的,因为我在Dispatch
方法中实例化它在尝试杀死它之前CaseDispatcher
类。这是我的代码片段:
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);
}
}
CaseDispatcher
上课:
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;
}
CaseAPI
上课:
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;
}
感谢您的关注,并对此表示感谢。
答案 0 :(得分:1)
我相信IsRunning属性是个问题。因为TaskCompletionSource并不真正知道你启动了外部进程,所以它处于WaitingForActivation状态。这是一个简化的例子来说明:
var tsc = new TaskCompletionSource<int>();
Task.Factory.StartNew(() =>
{
Thread.Sleep(10000);
tsc.SetResult(10);
});
var tmp = tsc.Task;
TaskStatus status = tmp.Status;
while (status != TaskStatus.RanToCompletion)
{
status = tmp.Status;
Thread.Sleep(1000);
Console.WriteLine(status);
}
请注意,在切换到RanToCompletion之前,它会继续说WaitingForActivation。有关此问题的更多讨论,请参阅this answer。简而言之,如果任务是由TaskCompletionSource创建的,它将永远不会进入运行状态。您必须自己管理IsRunning属性。