ca9*_*3d9 22 c# parallel-processing c#-4.0
我正在编写一个C#程序,通过FTP生成并上传50万个文件.我想并行处理4个文件,因为机器有4个核心,文件生成需要更长的时间.是否可以将以下Powershell示例转换为C#?或者是否有更好的框架,如C#中的Actor框架(如F#MailboxProcessor)?
$maxConcurrentJobs = 3;
# Read the input and queue it up
$jobInput = get-content .\input.txt
$queue = [System.Collections.Queue]::Synchronized( (New-Object System.Collections.Queue) )
foreach($item in $jobInput)
{
$queue.Enqueue($item)
}
# Function that pops input off the queue and starts a job with it
function RunJobFromQueue
{
if( $queue.Count -gt 0)
{
$j = Start-Job -ScriptBlock {param($x); Get-WinEvent -LogName $x} -ArgumentList $queue.Dequeue()
Register-ObjectEvent -InputObject $j -EventName StateChanged -Action { RunJobFromQueue; Unregister-Event $eventsubscriber.SourceIdentifier; Remove-Job $eventsubscriber.SourceIdentifier } | Out-Null
}
}
# Start up to the max number of concurrent jobs
# Each job will take care of running the rest
for( $i = 0; $i -lt $maxConcurrentJobs; $i++ )
{
RunJobFromQueue
}
Run Code Online (Sandbox Code Playgroud)
更新:
与远程FTP服务器的连接可能很慢,所以我想限制FTP上传处理.
Jeb*_*Jeb 17
任务并行库是你的朋友.请参阅此链接,其中介绍了您可以使用的内容.基本上框架4附带它,它将这些基本上后台线程池化的线程优化为正在运行的机器上的处理器数量.
也许是这样的:
ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 4;
Run Code Online (Sandbox Code Playgroud)
然后在你的循环中,例如:
Parallel.Invoke(options,
() => new WebClient().Upload("http://www.linqpad.net", "lp.html"),
() => new WebClient().Upload("http://www.jaoo.dk", "jaoo.html"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
34668 次 |
| 最近记录: |