问题描述
我想在Powershell中将某些文件解析操作与网络活动并行化.快速谷歌,启动线程看起来像一个解决方案,但是:
I want to parallelize some file-parsing actions with network activity in powershell. Quick google for it, start-thread looked like a solution, but:
当我尝试开始工作时,发生了同样的事情.
The same thing happened when I tried start-job.
我还尝试摆弄 System.Threading.Thread
[System.Reflection.Assembly]::LoadWithPartialName("System.Threading")
#This next errors, something about the arguments I can't figure out from the documentation of .NET
$tstart = new-object System.Threading.ThreadStart({DoSomething})
$thread = new-object System.Threading.Thread($tstart)
$thread.Start()
所以,我认为最好的办法是使用启动线程时知道我做错了什么,因为它似乎对其他人有用.我使用v2.0,不需要向下兼容.
So, I think the best would be to know what I do wrong when I use start-thread, because it seems to work for other people. I use v2.0 and I don't need downward compatibility.
推荐答案
Powershell没有名为Start-Thread的内置命令.
Powershell does not have a built-in command named Start-Thread.
V2.0确实具有PowerShell作业,这些作业可以在后台运行,并且可以被视为等同于线程.您可以使用以下命令来处理作业:
V2.0 does, however, have PowerShell jobs, which can run in the background, and can be considered the equivalent of a thread. You have the following commands at your disposal for working with jobs:
Name Category Synopsis
---- -------- --------
Start-Job Cmdlet Starts a Windows PowerShell background job.
Get-Job Cmdlet Gets Windows PowerShell background jobs that are running in the current ...
Receive-Job Cmdlet Gets the results of the Windows PowerShell background jobs in the curren...
Stop-Job Cmdlet Stops a Windows PowerShell background job.
Wait-Job Cmdlet Suppresses the command prompt until one or all of the Windows PowerShell...
Remove-Job Cmdlet Deletes a Windows PowerShell background job.
以下是有关如何使用它的示例.要开始工作,请使用start-job并传递一个脚本块,其中包含要异步运行的代码:
Here is an example on how to work with it. To start a job, use start-job and pass a script block which contains the code you want run asynchronously:
$job = start-job { get-childitem . -recurse }
此命令将启动一个作业,该作业将递归地将所有子级递归到当前目录下,并且您将立即返回命令行.
This command will start a job, that gets all children under the current directory recursively, and you will be returned to the command line immediately.
您可以检查$job
变量以查看作业是否完成,等等.如果要等待作业完成,请使用:
You can examine the $job
variable to see if the job has finished, etc. If you want to wait for a job to finish, use:
wait-job $job
最后,要接收工作的结果,请使用:
Finally, to receive the results from a job, use:
receive-job $job
这篇关于Powershell中的线程如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!