ForEachAsync不运行任务异步

时间:2017-11-07 11:27:47

标签: c# multithreading asynchronous async-await task-parallel-library

我按照这里的实施: ForEachAsync implementation

所以我有这个方法:

     public  static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, ConcurrentStack<FileInfo>, string, Task> body, ConcurrentStack<FileInfo> cStack, string fileName)
        {
              return  TaskEx.WhenAll(
                from partition in Partitioner.Create(source).GetPartitions(dop)
                select TaskEx.Run(async delegate
                {
                    using (partition)
                        while (partition.MoveNext())
                            await body(partition.Current, cStack, fileName);
                }));
        }

我用它就像:

var sw2 = new Stopwatch();
sw2.Start();
await rootDirTopLevelDirectories.ForEachAsync<string>(1, async (directoryPath, concurrentFoundedFilesStack, fileName) =>
                        {
                            await TaskEx.Run(() =>
                            {
                                Thread.Sleep(2000);
                            });

                            var f = string.Format("{0}*.{1}", fileName, "docx");
                            var sa = _fileSystemOperationsService.SearchForMostRecentFileUnderDirectoryByPattern(f, directoryPath, true, true);
                            concurrentFoundedFilesStack.Push(sa);
                        }, cStack, certFileName);

sw2.Stop();
Logger.GetInstance().Log(String.Format("ForEachAsync Takes {0}", sw2.ElapsedMilliseconds), System.Diagnostics.TraceEventType.Information);

现在,秒表显示它需要大约23秒,而rootDirTopLevelDirectories包含11个项目,这意味着线程运行同步。不同步(11 * 2秒)= 22秒。所以我想念一些东西吗?

0 个答案:

没有答案