【发布时间】:2017-06-16 14:25:12
【问题描述】:
如果我在一个线程上这样做会发生什么:
await Task.WhenAll(items.select(x => SomeAsyncMethod(x)))
// Where SomeAsyncMethod is defined like this (writeAsync is pure async io)
async Task SomeAsyncMethod(Item item){
await myDevice.writeAsync(...).ConfigureAwait(false);
//do some cpu intensive stuff...
}
并假设items 中有 10.000 个项目。当每个SomeAsyncMethod 在等待之后继续时,它会在线程池中的一个线程上执行此操作。因此,当许多SomeAsyncsMethods 返回时,线程池中的多个线程会同时被占用,或者在这种情况下,在任何给定时刻只有一个线程在SomeAsyncMethod 中执行“做一些 CPU 密集型工作”?
更新:好的,这是一个示例程序。当我在具有 8 个逻辑内核的 PC 上进行测试时,minthreads 为 12 或 13,而 maxthreads 在 35-40 范围内结束。 所以看起来好像最多将创建 4 个线程作为逻辑核心。创建 10.000 或 100.000 个文件无关紧要 - 使用相同的最大线程数 - 也许这是因为所有任务都排队等待访问文件系统?请注意,该程序将在 c:\tmp\asynctest 中创建大量小文件:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication4 {
internal class Program {
private static void Main(string[] args) {
var myDevice = new MyDevice();
var ints = new List<int>();
for (var i = 0; i < 10000; i++) {
ints.Add(i);
}
var task = Task.WhenAll(ints.Select(i => myDevice.WriteTextAsync(i.ToString())));
task.Wait();
Console.WriteLine("Max thread count = " + myDevice.MaxThreadCount);
Console.WriteLine("Min thread count = " + myDevice.MinThreadCount);
Console.ReadLine();
}
}
public class MyDevice {
public ConcurrentDictionary<string, string> ThreadIds;
public int MaxThreadCount;
public int MinThreadCount = Process.GetCurrentProcess().Threads.Count;
public async Task WriteTextAsync(string text) {
var filePath = @"c:\tmp\asynctest\" + text + ".txt";
var encodedText = Encoding.Unicode.GetBytes(text);
using (var sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) {
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length).ConfigureAwait(false);
MaxThreadCount = Math.Max(MaxThreadCount, Process.GetCurrentProcess().Threads.Count);
MinThreadCount = Math.Min(MinThreadCount, Process.GetCurrentProcess().Threads.Count);
}
}
}
}
更新 2。现在,如果我启动多个线程,每个线程同时执行大量 aysnc io 任务,那么与更新 1 中的单线程示例相比,看起来总共使用的线程并不多。在测试中我只是运行,其中 10.000 个文件由 4 个线程创建,然后最大线程为 41,最小线程为 12 - 所以似乎有一些集中控制用于异步任务延续的线程数。这是一个示例,其中 4 个线程分别启动 10.000 个异步操作:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication4 {
internal class Program {
private static void Main(string[] args) {
var myDevice = new MyDevice();
var ints = new List<int>();
const int limit = 10000;
for (var i = 0; i < limit; i++) {
ints.Add(i);
}
List<Task> jobs = new List<Task>();
for (var j = 0; j < 4*limit; j+=limit) {
var jobid = j;
jobs.Add(Task.Run(() => Runjob(ints, myDevice, jobid)));
}
Task.WaitAll(jobs.ToArray());
Console.WriteLine("Max thread count = " + myDevice.MaxThreadCount);
Console.WriteLine("Min thread count = " + myDevice.MinThreadCount);
Console.ReadLine();
}
private static void Runjob(List<int> ints, MyDevice myDevice, int jobid) {
Console.WriteLine("Starting job " + jobid);
var task = Task.WhenAll(ints.Select(i => myDevice.WriteTextAsync((jobid+i).ToString())));
task.Wait();
Console.WriteLine("Finished job " + jobid);
}
}
public class MyDevice {
public int MaxThreadCount;
public int MinThreadCount = Process.GetCurrentProcess().Threads.Count;
public async Task WriteTextAsync(string text) {
var filePath = @"c:\tmp\asynctest\" + text + ".txt";
var encodedText = Encoding.Unicode.GetBytes(text);
using (var sourceStream = new FileStream(filePath,
FileMode.Append, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) {
await sourceStream.WriteAsync(encodedText, 0, encodedText.Length).ConfigureAwait(false);
MaxThreadCount = Math.Max(MaxThreadCount, Process.GetCurrentProcess().Threads.Count);
MinThreadCount = Math.Min(MinThreadCount, Process.GetCurrentProcess().Threads.Count);
}
}
}
}
【问题讨论】:
-
这一切都取决于。同步上下文。
-
最简单的发现方法就是尝试一下。添加
Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);并找出答案。 -
好的,假设我做了一个 ConfigureAwait false 以便不需要上下文(我现在编辑问题以反映这一点)。
-
如果是大量的项目,如您所说的 10 000。您可能会遇到线程饥饿。此外,我们需要考虑以下几点: ThreadPool 可以根据情况进行扩展。启动许多任务可能需要一些时间,其中一些第一个任务已经完成并为其他任务释放线程。
-
我没有对此进行测试,但我认为没有理由应该采用多个线程。恕我直言,只有一个线程执行这项工作。
标签: c# async-await