ずっと気になっていたので試してみた。
まず普通の Task.Factory.StartNew
。
Program.normal.cs
using System;
using System.Threading;
using System.Threading.Tasks;
namespace BackgroundTest
{
class Program
{
static void Main(string[] args)
{
int workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Console.WriteLine(workerThreads);
Console.WriteLine(completionPortThreads);
ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
Console.WriteLine(workerThreads);
Console.WriteLine(completionPortThreads);
Console.WriteLine("--");
Task.Factory.StartNew(() =>
{
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Console.WriteLine(workerThreads);
Console.WriteLine(completionPortThreads);
ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
Console.WriteLine(workerThreads);
Console.WriteLine(completionPortThreads);
while (true) { }
});
Console.Read();
}
}
}
次に TaskCreationOptions.LongRunning
を指定。
Program.long.cs
using System;
using System.Threading;
using System.Threading.Tasks;
namespace BackgroundTest
{
class Program
{
static void Main(string[] args)
{
int workerThreads, completionPortThreads;
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Console.WriteLine(workerThreads);
Console.WriteLine(completionPortThreads);
ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
Console.WriteLine(workerThreads);
Console.WriteLine(completionPortThreads);
Console.WriteLine("--");
Task.Factory.StartNew(() =>
{
ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads);
Console.WriteLine(workerThreads);
Console.WriteLine(completionPortThreads);
ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads);
Console.WriteLine(workerThreads);
Console.WriteLine(completionPortThreads);
while (true) { }
}, TaskCreationOptions.LongRunning);
Console.Read();
}
}
}
ということで、LongRunning
を指定すれば ThreadPool の利用可能ワーカースレッド数を減らさずに済むようだ。