限制C#中的并行线程数

ca9*_*3d9 22 c# parallel-processing c#-4.0

我正在编写一个C#程序,通过FTP生成并上传50万个文件.我想并行处理4个文件,因为机器有4个核心,文件生成需要更长的时间.是否可以将以下Powershell示例转换为C#?或者是否有更好的框架,如C#中的Actor框架(如F#MailboxProcessor)?

Powershell的例子

$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上传处理.

Aus*_*nen 31

假设您使用TPL构建它,您可以将ParallelOptions.MaxDegreesOfParallelism设置为您想要的任何内容.

Parallel.For 代码示例.


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)


Gio*_*rdi 5

如果您使用的是.Net 4.0,则可以使用并行库

假设您正在通过使用Parallel Foreach来对可以"并行"迭代的50万个文件进行迭代, 或者您可以查看PLinq 这里两者之间的比较