1

我不是线程专家,但我想一次并行运行一个函数 N 次,如果需要,可以使用多个内核。

我目前有以下代码:

tasks = new List<Task>();
for (int i = 0; i < _runThreads; i++)
{
    tasks.Add(Task.Factory.StartNew(() =>
    {
        GetRSS();
    }, stopAllTasks.Token));
}

获取RSS 示例:

private void GetRSS()
{
    while (!queue.IsEmpty)
    {
        int total = 0;
        // dequeue, get url bla bla
        using (WebClient client = new WebClient())
        {
            //some code here get html content
        }
        // parse the rss bla bla
        // get the count of total items found 
        // update total variable with the total

        Interlocked.Add(ref counter, total);
    }
}

如您所见,在 GetRSS 代码中,我正在counter使用它获得的每页总条目数进行更新,因为我的计时器滴答作响,它将计数器的值更新为标签,以便我可以看到进度。

由此,我注意到这些任务并没有同时工作,但实际上它们是一个一个地工作,因为计数器只更新 X 数量,这相当于运行一个函数。

所以从那里我相信上面的代码实际上并没有并行运行任务,但它们似乎是按顺序运行的。

  • 是对的吗 ?

  • 如果是这样,我如何转换我的代码以便它实际并行运行?

4

1 回答 1

2

您的代码绝对应该并行运行。在这里查看类似的问题。

此外,您可能会面临连接限制,这就是为什么您可以认为它是按顺序运行的。您可以使用配置来覆盖它:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.net>
        <connectionManagement>
            <add address="*" maxconnection="<some reasonable number here>" />
        </connectionManagement>
    </system.net>
</configuration>
于 2012-06-21T21:45:48.370 回答