How can i create new thread and running in async? i have an event which should update text box in run time so i need to run it in different thread. (powershell 2). How can i do it in PowerShell?
-
As if you provide a little code sample I could add some sample code to my answer.Adam Driscoll– Adam Driscoll2010-09-14 16:25:03 +00:00Commented Sep 14, 2010 at 16:25
-
You could also do this with Powershell events , which run a action when the event occurs. This just means you dont need to worry about other threads/jobs etcRC1140– RC11402010-09-16 15:48:59 +00:00Commented Sep 16, 2010 at 15:48
Add a comment
|
2 Answers
Background Jobs are what you are looking for.
http://msdn.microsoft.com/en-us/library/dd878288(VS.85).aspx
Here's a few examples from help:
Starting a job with Start-Job:
C:\PS>start-job -scriptblock {get-process}
Id Name State HasMoreData Location Command
--- ---- ----- ----------- -------- -------
1 Job1 Running True localhost get-process
Starting a job with the AsJob parameter:
C:\PS>$jobWRM = invoke-command -computerName (get-content servers.txt) -scriptblock {get-service winrm} -jobname WinRM -throttlelimit 16 -AsJob
Comments
This is a working solution in PowerShell 5 to plays a ScriptBlock in a System.Threading.Thread. You can also pass arguments in Thread.Start(args[]) and add param(parameters[]) to ScriptBlock. There is many other ways to get independent threads in PowerShell, but this is the way I founded for use original System.Threading.Thread;
$mainthread = [System.Threading.Thread]::CurrentThread | Out-String;
[Console]::Write($mainthread);
[ScriptBlock] $scr = {
[System.Threading.Thread]::Sleep(4000);
$secondthread = [System.Threading.Thread]::CurrentThread | Out-String;
[Console]::Write($secondthread);
}
$ts = New-Object System.Threading.ParameterizedThreadStart($scr, $scr.GetType().GetMethod("Invoke").MethodHandle.GetFunctionPointer());
$newthread = [System.Threading.Thread]::new($ts);
$newthread.Start();
[System.Threading.Thread]::Sleep(500);
Write-Host 1;
[System.Threading.Thread]::Sleep(500);
Write-Host 2;
[System.Threading.Thread]::Sleep(500);
Write-Host 3;
[System.Threading.Thread]::Sleep(500);
Write-Host 4;
Read-Host;