我正在使用 C# 调用 powershell 命令,并且 powershell 命令在后台调用。我想终止后台线程。每次,我终止后台线程时,powershell仍在运行,这导致我无法再次运行该线程。有什么方法可以终止powershell执行吗?
后台线程如下:
Task.run(()=>{ while(...) {...
if (cancellationToken.IsCancellationRequested)
{
cancellationToken.ThrowIfCancellationRequested();
}}});
Task.run(()=>{
while(...) { powershell.invoke(powershellCommand);// it will execute here, I don't know how to stop.
} })
Run Code Online (Sandbox Code Playgroud)
我知道我迟到了,但我刚刚编写了一个扩展方法,它将调用粘合BeginInvoke()到EndInvoke()任务并行库(TPL)中:
public static Task<PSDataCollection<PSObject>> InvokeAsync(this PowerShell ps, CancellationToken cancel)
{
return Task.Factory.StartNew(() =>
{
// Do the invocation
var invocation = ps.BeginInvoke();
WaitHandle.WaitAny(new[] { invocation.AsyncWaitHandle, cancel.WaitHandle });
if (cancel.IsCancellationRequested)
{
ps.Stop();
}
cancel.ThrowIfCancellationRequested();
return ps.EndInvoke(invocation);
}, cancel);
}
Run Code Online (Sandbox Code Playgroud)
由于Stop()PowerShell 类上的方法,停止 PowerShell 脚本非常简单。
CancellationToken如果您想异步调用脚本,可以轻松使用 a 进行连接:
using(cancellationToken.Register(() => powershell.Stop())
{
await Task.Run(() => powershell.Invoke(powershellCommand), cancellationToken);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3511 次 |
| 最近记录: |