2

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?

2
  • As if you provide a little code sample I could add some sample code to my answer. Commented 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 etc Commented Sep 16, 2010 at 15:48

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.