Reputation: 105
I'm invoking powershell command with C#, and powershell command is invoked background. and i want to terminate the background thread. everytime, i terminate the background thread, the powershell is still running which result in that i can't run that thread again. is there any method to terminate powershell execution?
the background thread as follows:
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.
} })
Upvotes: 4
Views: 3866
Reputation: 700
Using Task.Factory.FromAsync
:
await Task.Factory.FromAsync(shell.BeginInvoke(), shell.EndInvoke)
.WaitAsync(cancellationToken)
.ConfigureAwait(false);
This allows the cancellation token to be registered elsewhere in the code so additional side effects can be added when execution is cancelled if desired.
Upvotes: 0
Reputation: 614
I know I'm late to the party but I've just written an extension method which glues up the calls to BeginInvoke()
and EndInvoke()
into Task Parallel Library (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);
}
Upvotes: 6
Reputation: 39625
Stopping a PowerShell script is pretty simple thanks to the Stop()
method on the PowerShell class.
It can be easily hooked into using a CancellationToken
if you want to invoke the script asynchronously:
using(cancellationToken.Register(() => powershell.Stop())
{
await Task.Run(() => powershell.Invoke(powershellCommand), cancellationToken);
}
Upvotes: 5