執行URL指向同一服務器?如果是這樣,可能是因爲您正在達到HTTP連接限制,而不是線程限制。有一個簡單的方法來告訴 - 將您的代碼更改爲:
int threads = 10;
Dictionary<string, string> results = urls.AsParallel(threads)
.ToDictionary(url => url,
url => {
Console.WriteLine("On thread {0}",
Thread.CurrentThread.ManagedThreadId);
return GetPage(url);
});
編輯:嗯。我不能得到ToDictionary()
並行在所有與一些示例代碼。它適用於Select(url => GetPage(url))
,但不是ToDictionary
。會搜索一下。
編輯:好的,我仍然不能得到ToDictionary
並行,但你可以解決這個問題。這裏有一個簡短但完整的程序:
using System;
using System.Collections.Generic;
using System.Threading;
using System.Linq;
using System.Linq.Parallel;
public class Test
{
static void Main()
{
var urls = Enumerable.Range(0, 100).Select(i => i.ToString());
int threads = 10;
Dictionary<string, string> results = urls.AsParallel(threads)
.Select(url => new { Url=url, Page=GetPage(url) })
.ToDictionary(x => x.Url, x => x.Page);
}
static string GetPage(string x)
{
Console.WriteLine("On thread {0} getting {1}",
Thread.CurrentThread.ManagedThreadId, x);
Thread.Sleep(2000);
return x;
}
}
那麼,這有多少線程使用? 5.爲什麼?善良知道。我有2個處理器,所以不是這樣 - 我們已經指定了10個線程,所以不是這樣。即使我更改GetPage
來錘擊CPU,它仍然使用5。
如果您只需要將其用於一項特定任務 - 並且您不介意稍微有點臭的代碼 - 說實話,您可能最好自己實施它。
我得到了相同的症狀。我運行你的分析,並得到只有一個線程..我想性能從1增加到2線程我看到在我的腦海 – 2009-03-04 20:57:23