簡體   English   中英

並行編程C#-TPL-更新共享變量和建議

[英]Parallel Programming C# - TPL - Update Shared Variable & Suggestions

我是並行編程的新手,實際上這是我第一次嘗試。 我目前正在.NET 4中做一個項目,並且希望有4或5個並行執行。

我看到一些選擇。 Task.Factory.StartNew Parallel.For Parallel.ForEach等。

我要做的是發布到網站上並獲取大約200個URL的響應。

當我使用Parallel.ForEach我找不到控制線程數的方法,並且應用程序使用了130多個線程,並且網站無響應:)

我對在for循環中使用Task.Factory.StartNew感興趣,並將URL分為4個或5個任務。

List<Task> tasks = new List<Task>();
for (int i = 0; i < 5; i++)
{
    List<string> UrlForTask = GetUrlsForTask(i,5); //Lets say will return some thing like 1 of 5 of the list of URLs
    int j = i;
    var t = Task.Factory.StartNew(() =>
    {
        List<PageSummary> t = GetSummary(UrlForTask);
        Summary.AddRange(t); //Summary is a public variable
    }
    tasks.Add(t);
}

我相信這些任務可以歸結為線程。 因此,如果我將SummaryList<PageSummary>它是否是線程安全的(我知道多個線程訪問共享變量存在問題)?

這是我們應該使用ConcurrentQueue<T>嗎?

您是否知道一個好的資源,可以幫助您了解通過多個任務等訪問和更新共享變量?

您可能會想到,我可以用於此類任務的最佳方法是什么?

Parallel.ForEach具有采用ParallelOptions實例的重載。 MaxDegreeOfParallelism屬性是您需要使用的屬性。

List<MyRequest> requests = ...;
BlockingCollection<MyResponse> responses = ...;
Task.Factory.StartNew(() =>
{
    Parallel.ForEach(
        requests,
        new ParallelOptions { MaxDegreeOfParallelism = 4 },
        request => responses.Add(MyDownload(request)));
    responses.CompleteAdding();
});

foreach (var response in responses.GetConsumingEnumerable())
{
    Console.WriteLine(response.MyMessage);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM