は、私は、より高いデフォルト値にMinThreadsを設定When to use TaskCreationOptions.LongRunning?
への回答を含むThreadPool.SetMinThreadsとTaskCreationOptions.LongRunningにいくつかの読書は、私の場合は大きな違いを作りました。私は、単純なバックグラウンドプロセスを作成して、テスト実行中にThreadPoolのAvailable Threadsが大幅に変化していて、MinThreadsの値を超えていたかどうかを確認しました。
私が診断に使用したコードは次のとおりです。本番用ではありません。ここに示すスレッドの使用状況のレポートは、最初に増加した場合にのみ面白いでしょう。また、タイマーには経過時にスレッドが必要なので、利用可能なスレッドを待つ必要もあります。
静的varsの:起動時に
private static Timer _timer;
private static int _lastActiveThreads;
private static int _lastAvailableThreads;
private static int _maxThreads;
private static int _minThreads;
ラン:
int completionPortThreads;
ThreadPool.GetMaxThreads(out _maxThreads, out completionPortThreads);
ThreadPool.GetMinThreads(out _minThreads, out completionPortThreads);
_timer = new Timer
{
AutoReset = true,
Interval = 500,
};
_timer.Elapsed += TimerElasped;
_timer.Start();
経過方法:
private static void TimerElasped(object sender, ElapsedEventArgs e)
{
int minWorkerThreads;
int availWorkerThreads;
int completionPortThreads;
ThreadPool.GetMinThreads(out minWorkerThreads, out completionPortThreads);
ThreadPool.GetAvailableThreads(out availWorkerThreads, out completionPortThreads);
var activeThreads = _maxThreads - availWorkerThreads;
if (availWorkerThreads != _lastAvailableThreads)
{
_lastAvailableThreads = availWorkerThreads;
if (activeThreads > _lastActiveThreads)
{
_lastActiveThreads = activeThreads;
Logger.Log($"+++++ Active Threads is now: {activeThreads}");
if (activeThreads > _minThreads)
{
var diff = activeThreads - _minThreads;
Logger.Log($"+++++ Active threads is now {activeThreads}, which is {diff} more than minThread value of {_minThreads}. This may be causing delays.");
}
}
}
}
あなたは 'TaskCreationOptions.LongRunningを指定せずに、一度に多くの長時間実行タスクを開始しています'?もしあなたがそうした場合、デフォルトのスケジューラは新しいスレッドを割り当てる前に500ミリ秒のようなものを待っているので、起動するには新しい生存予定の短いタスクは起動時に*巨大な遅延を経験します。 'ThreadPool.SetMinThreads'で修正することができますが、パフォーマンスの低下を防ぐために、長時間実行する方がよいでしょう。 – Sinatr
興味深い。これは同期コードにも当てはまりますか? –
@Sinatr *長期間実行されていないタスクは、スレッドスターベーションがないようにする方法です。 'LongRunning'を使ってたくさんのタスクを作成するのは、スレッドの飢餓をどのように作成するかです。 – Servy