Tahir Hassan
Tahir Hassan

Reputation: 5817

PowerShell's Stop-Job / StopJob() takes 2 minutes to stop job

I have written a library using C# and use it within a PowerShell script. The C# library loads a large amount of data into a database. I am using Start-Job to kick off the process and I am monitoring a file for errors.

However, I have found that even a simple while loop in C# cannot be stopped (takes two whole minutes).

My C#:

namespace SampleJobDLL
{
    public class ClassX
    {
        public void MethodY()
        {
            while (true)
            {
                Console.WriteLine("hello");
            }
        }
    }
}

PowerShell:

$scriptBlock = {

    Add-Type -Path ".\SampleJobDLL.dll"

    $classX = New-Object SampleJobDLL.ClassX

    $classX.MethodY();
}

$job = Start-Job -ScriptBlock $scriptBlock

Then running the following script:

$before = [DateTime]::Now; 
$job.StopJob(); 
$after = [DateTime]::Now; 
$after.Subtract($before);

Gives me:

Days              : 0
Hours             : 0
Minutes           : 2
Seconds           : 0
Milliseconds      : 4

Is there any method of running code using Start-Job (or equivalent command) but being able to stop it immediately?

Upvotes: 4

Views: 2675

Answers (1)

Tahir Hassan
Tahir Hassan

Reputation: 5817

I believe that dfundako and user2460798 are right: it is easiest to spawn a new process and kill it, rather than messing around with PowerShell Jobs.

Put the script block contents in a new file; call it (e.g) MyScript.ps1.

Thereafter, we launch the script using Start-Process and capture the process object in a variable:

$process = Start-Process powershell.exe '.\MyScript.ps1' -PassThru

Kill it using

$process.Kill();

or

Stop-Process -Id $process.Id -Force

I have looked into creating a PowerShell instance using [PowerShell]::Create() but a command cannot be invoked against an instance while it is running some other code.

Also looked into spawning a new thread, which does not work (even if I pass in -Mta as a command line arg to powershell.exe).

Upvotes: 1

Related Questions