我目前正在編寫一個站點地圖生成器,它爲站點刮取網址並生成一個XML站點地圖。由於大部分等待都花在了對uri的請求上,所以我正在使用線程,特別是ThreadPool對象中的構建。在C#中線程的未知數量的線程#
爲了讓主線程等待未知數量的線程完成我已經實現了以下設置。我不覺得這是一個很好的解決方案,任何線程專家都可以告訴我這個解決方案有什麼問題,或者提出一個更好的實現方法?
的的EventWaitHandle設置爲EventResetMode.ManualReset
這裏是線程方法
protected void CrawlUri(object o)
{
try
{
Interlocked.Increment(ref _threadCount);
Uri uri = (Uri)o;
foreach (Match match in _regex.Matches(GetWebResponse(uri)))
{
Uri newUri = new Uri(uri, match.Value);
if (!_uriCollection.Contains(newUri))
{
_uriCollection.Add(newUri);
ThreadPool.QueueUserWorkItem(_waitCallback, newUri);
}
}
}
catch
{
// Handle exceptions
}
finally
{
Interlocked.Decrement(ref _threadCount);
}
// If there are no more threads running then signal the waithandle
if (_threadCount == 0)
_eventWaitHandle.Set();
}
這裏是主線程方法
// Request first page (based on host)
Uri root = new Uri(context.Request.Url.GetLeftPart(UriPartial.Authority));
// Begin threaded crawling of the Uri
ThreadPool.QueueUserWorkItem(_waitCallback, root);
Thread.Sleep(5000); // TEMP SOLUTION: Sleep for 5 seconds
_eventWaitHandle.WaitOne();
// Server the Xml Sitemap
context.Response.ContentType = "text/xml";
context.Response.Write(GetXml().OuterXml);
任何想法非常讚賞:)
這看起來很有趣,謝謝。我希望有機會在週末嘗試一下。我不能相信我忘記了異步請求:o – WDuffy 2009-05-01 07:03:28