标签: parallel.foreach

如何提高 Parallel.ForEach 的吞吐量

我尝试通过并行执行来优化代码,但有时只有一个线程承担所有重负载。下面的例子展示了如何在最多 4 个线程中执行 40 个任务,并且前十个任务比其他的更耗时。

Parallel.ForEach似乎将数组分成 4 部分,并让一个线程处理每个部分。所以整个执行过程大约需要 10 秒。它应该能够在最多 3.3 秒内完成!

有没有办法一直使用所有线程,因为在我的实际问题中不知道哪些任务耗时?

var array = System.Linq.Enumerable.Range(0, 40).ToArray();

System.Threading.Tasks.Parallel.ForEach(array, new System.Threading.Tasks.ParallelOptions() { MaxDegreeOfParallelism = 4, },
     i =>
     {
         Console.WriteLine("Running index {0,3} : {1}", i, DateTime.Now.ToString("HH:mm:ss.fff"));
         System.Threading.Thread.Sleep(i < 10 ? 1000 : 10);
     });
Run Code Online (Sandbox Code Playgroud)

c# .net-4.0 parallel.foreach

3
推荐指数
2
解决办法
3430
查看次数

如何在 Parallel.ForEach 期间添加或更新 ConcurrentDictionary?

我有一个文件列表,其中每个文件都包含一个Foo数据列表。现在,同一段 Foo 数据(例如Id = 1)可能存在于多个文件中,但最新的数据将覆盖现有的数据。

我只是将每条数据读入内存集合中。

if !cache.HasKey(foo.Id) then Add    
else cache[foo.Id].UpdatedOn < foo.UpdatedOn then Update  
else do nothing
Run Code Online (Sandbox Code Playgroud)

当我阅读文件时(因为其中有一些),我也在使用Parallel.ForEach(files, file => { .. });

我不知道我该怎么做。

我正在考虑使用 aConcurrentDictionary但我不确定如何使用AddOrUpdatewhere子句

有什么建议么?

.net c# parallel-processing concurrentdictionary parallel.foreach

3
推荐指数
1
解决办法
1478
查看次数

使用 VB.Net Parallel.ForEach 和 ConcurrentDictionary 的正确语法是什么?

我很难使用 Parallel.ForEach 和 ConcurrentDictionary 获得正确的语法。下面 Parallel.ForEach 的正确语法是什么?

Dim ServerList as New ConcurrentDictionary(Of Integer, Server)
Dim NetworkStatusList as New ConcurrentDictionary(Of Integer, NetworkStatus)

... (Fill the ServerList with several Server class objects)

'Determine if each server is online or offline.  Each call takes a while...
Parallel.ForEach(Of Server, ServerList, Sub(myServer)
        Dim myNetworkStatus as NetworkStatus = GetNetworkStatus(myServer)
        NetworkStatusList.TryAdd(myServer.ID, myNetworkStatus)
    End Sub

... (Output the list of server status to the console or whatever)
Run Code Online (Sandbox Code Playgroud)

vb.net parallel-processing parallel.foreach

3
推荐指数
1
解决办法
1万
查看次数

通过多线程调用静态方法 - 它们可以干扰彼此的输入参数吗

我的代码被 AJAX UI(多线程)调用,并在数据处理后发送 Json 输出。最近在重构代码时,我们将许多常见和重复的方法转移到一个单独的文件中,在那里我们将它们设为静态,因为我们没有处理任何静态/共享数据。以下是我们静态方法的示例设计:

public class Helper
{
   public static C Method1(List<A> aList, List<B> bList)
   {
      C objC = new C();

      // Create ObjC based on inputs aList and bList

      return objC;
   }
}
Run Code Online (Sandbox Code Playgroud)

现在,我的理解是以下调用不会有问题,在 Parallel.foreach 或任何其他多线程场景中调用时,请验证。

C resultC = Helper.Method1(aList, bList);
Run Code Online (Sandbox Code Playgroud)

但是我们怀疑,是否有一种罕见的情况可能是两个线程进行上述调用并且aList,bList的一个线程数据被另一个线程替换,从而给出有缺陷的结果(可能是异常),这可以为问题将无法调试和重复,因为两个线程必须在精确的毫秒内同时执行/执行该方法所需的时间

请分享您的观点,我们是否在正确的轨道上创建上述设计,或者有我们无法看到的坑。我们可以很容易地通过实例方法替换,在这种情况下它们肯定是线程安全的,因为每个线程都有自己的实例可以使用,但是我觉得可能不需要并且继续创建实例很麻烦,当我们可以方便地使用时静态调用。

请注意,到目前为止我还没有看到代码运行出现问题,但正如我所说,如果发生这种情况,这将是极端情况,两个线程同时出现,一个线程替换输入参数,而另一个线程仍在处理结果。

c# multithreading static-methods task-parallel-library parallel.foreach

3
推荐指数
1
解决办法
4061
查看次数

Parallel.ForEach&lt;T&gt; 的某些项目在 ThreadPool 上运行,有些则不在

我有一个像这样的简单算法:

Parallel.ForEach(myList, new ParallelOptions() { MaxDegreeOfParallelism = 4 } ,(job) => job.doSomething());  
Run Code Online (Sandbox Code Playgroud)

myList是一个List<MyType>.

MyTypevoid DoSomething()

DoSomething我检查里面Thread.CurrentThread.IsThreadPoolThread。有些线程不是“ThreadPooled”;

c# multithreading threadpool task-parallel-library parallel.foreach

3
推荐指数
1
解决办法
74
查看次数

MaxDegreeOfParallelism 不适用于任务列表?

我有一个任务列表,我想以有限的方式并行执行,几乎就像批处理,而无需我管理它。我的方法是使用 Parallel.ForEach 和 ParallelOptions 的 MaxDegreeOfParallelism 属性。我发现无论我将值设置为多少,所有任务都会同时启动。这是不受欢迎的行为。我希望同时执行的任务数量等于该属性。我写了一个简单的例子来说明

class Program
{
    static void Main(string[] args)
    {
        var numbers = Enumerable.Range(1, 5);
        var tasks = new List<Task>();

        foreach (int number in numbers)
        {
            tasks.Add(new Task(() => {Console.WriteLine("Starting thread {0} at time {1}. Starting delay...", Thread.CurrentThread.ManagedThreadId, DateTime.Now);
            Thread.Sleep(1000);
            Console.WriteLine("{0} is done at {1}.", Thread.CurrentThread.ManagedThreadId, DateTime.Now);}));
        }

        Parallel.ForEach(tasks, new ParallelOptions() { MaxDegreeOfParallelism = 2 }, t =>
        {
            t.Start();
        });

        Task.WaitAll(tasks.ToArray());
    }
}
Run Code Online (Sandbox Code Playgroud)

这是输出: 控制台输出

我的方法或理解不正确吗?

c# task task-parallel-library parallel.foreach

3
推荐指数
1
解决办法
1154
查看次数

使用 C# Parallel.ForEach 循环处理 SFTP 文件不处理下载

我正在使用 Renci SSH.NET 软件包版本 2016。我正在从外部服务器下载文件。我通常每 6 秒就能下载一个文件,当你有数千个文件时,这很糟糕。我最近尝试将foreach循环更改为Parallel.ForEach. 这样做将文件下载时间更改为 1.5 秒。除了当我检查文件时,它们都是 0 KB,因此它没有下载任何内容。并行循环有什么问题吗?我是 C# 新手,正在尝试缩短下载时间

Parallel.ForEach(summary.RemoteFiles, (f, loopstate) =>
{
    //Are we still connected? If not, reestablish a connection for up to a max of "MaxReconnectAttempts" 
    if (!sftp.IsConnected)
    {
        int maxAttempts = Convert.ToInt32(ConfigurationManager.AppSettings["MaxReconnectAttempts"]);

        StatusUpdate(this, new Types.StatusUpdateEventArgs() { message = "SFTP Service has been connected from remote system, attempting to reconnect (" + sftpConnInfo.Host + ":" + sftpConnInfo.Port.ToString() + remotePath + " - Attempt 1 of " …
Run Code Online (Sandbox Code Playgroud)

.net c# sftp parallel.foreach ssh.net

3
推荐指数
1
解决办法
2840
查看次数

从 IEnumerable&lt;Task&lt;T&gt;&gt; 到 IAsyncEnumerable&lt;T&gt; 通过在 Parallel.ForEach/Parallel.ForEachAsync 内返回的yield 给出错误 CS1621

在 .NET 6 项目中,我必须调用一个偏移分页(页/每页)的 Web API,并且我希望尽可能使 n 个调用并行。

这是使用给定页码调用 API 一次的方法:

private Task<ApiResponse> CallApiAsync(int page,
    CancellationToken cancellationToken = default)
{
    return GetFromJsonAsync<ApiResponse>($"...&page={page}", cancellationToken)
        .ConfigureAwait(false);
}
Run Code Online (Sandbox Code Playgroud)

我实际上需要的是从第 1 页到第 n 页的所有 API 调用的仅前向流式迭代器,因此考虑到这一要求,我认为这IAsyncEnumerable是正确的 API,这样我就可以并行触发 API 调用并访问每个 API 响应一旦准备好,就可以完成,而不需要全部完成。

所以我想出了以下代码:

public async IAsyncEnumerable<ApiResponse> CallApiEnumerableAsync(int perPage,
    [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
    int numProducts = GetNumberOfProducts(perPage);

    int numCalls = MathExtensions.CeilDiv(numProducts, perPage);

    var pages = Enumerable.Range(1, numCalls);

    Parallel.ForEach(pages, async page => {
        yield return await CallApiAsync(page, cancellationToken).ConfigureAwait(false);
    });

    yield break;
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误 …

c# parallel.foreach .net-core iasyncenumerable parallel.foreachasync

3
推荐指数
1
解决办法
300
查看次数

与ListView的Parallel.ForEach

我有以下代码:

Parallel.ForEach(this.listView2.CheckedItems,
                    new ParallelOptions { MaxDegreeOfParallelism = 4 },
                    (CheckedItem) =>
                    {
                         //do something
                    });
Run Code Online (Sandbox Code Playgroud)

我得到以下编译错误:

无法从用法中推断出方法'System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner,System.Threading.Tasks.ParallelOptions,System.Action)'的类型参数.尝试显式指定类型参数.

我搜索了如何使用listview与任务,但找不到任何东西.

如何在ListView中使用Parallel.ForEach?

c# task-parallel-library parallel.foreach

2
推荐指数
1
解决办法
2043
查看次数

Parallel.ForEach给出了错误

我一直在尝试搜索我可以为Parallel.ForEach循环做些什么:

        selection.Words is Microsoft.Office.Interop.Word.Selection;
        //range is supposed to be a word.Range
        Parallel.ForEach(selection.Words, range =>
        {

        });
Run Code Online (Sandbox Code Playgroud)

这是我收到的错误,无法从用法中推断出方法" System.Threading.Tasks.Parallel.ForEach(System.Collections.Concurrent.OrderablePartitioner,System.Action)"的类型参数.请尝试明确指定类型参数. "

我一直在寻找一个美好的时光,但所有这些只是显示object.AsEnumerable()作为答案.然而,词语不能成为一个令人难忘的词汇.

c# parallel.foreach

2
推荐指数
1
解决办法
4838
查看次数