TaskCreationOptions.LongRunning


ずっと気になっていたので試してみた。

まず普通の 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();
        }
    }
}

GetAvailableThreads の戻り値が 1 減っている

次に 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();
        }
    }
}

GetAvailableThreads の戻り値に変化なし

ということで、LongRunning を指定すれば ThreadPool の利用可能ワーカースレッド数を減らさずに済むようだ。