ParallelOptions、TaskCreationOptions、および Task.Factory.StartNew(() => を正しく効率的に使用するために、どの方法が適切か (ある場合) 提案してください。
private void NeedToUse_MaxDegreeOfParallelism_Method1()
{
CancellationTokenSource tokenFor_task = new CancellationTokenSource();
ParallelOptions parOpts = new ParallelOptions();
//parOpts.CancellationToken = tokenFor_task_tpl_Pair01.Token;
parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;
//parOpts.TaskScheduler = TaskScheduler.Default;
TaskCreationOptions tco = new TaskCreationOptions();
tco = TaskCreationOptions.PreferFairness;
Task task = null;
task = Task.Factory.StartNew(() =>
{
while (!tokenFor_task.IsCancellationRequested)
{
LongRunningMethod();
}
}, tokenFor_task.Token, tco, TaskScheduler.Default);
}
private void NeedToUse_MaxDegreeOfParallelism_Method2()
{
//CancellationTokenSource tokenFor_task = new CancellationTokenSource();
ParallelOptions parOpts = new ParallelOptions();
parOpts.CancellationToken = tokenFor_task_tpl_Pair01.Token;
parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;
parOpts.TaskScheduler = TaskScheduler.Default;
TaskCreationOptions tco = new TaskCreationOptions();
tco = TaskCreationOptions.PreferFairness;
Task task = null;
task = Task.Factory.StartNew(() =>
{
while (!parOpts.CancellationToken.IsCancellationRequested)
{
LongRunningMethod();
}
}, parOpts.CancellationToken, tco, parOpts.TaskScheduler);
}
private void NeedToUse_MaxDegreeOfParallelism_Method3()
{
CancellationTokenSource tokenFor_task = new CancellationTokenSource();
ParallelOptions parOpts = new ParallelOptions();
//parOpts.CancellationToken = tokenFor_task_tpl_Pair01.Token;
parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;
//parOpts.TaskScheduler = TaskScheduler.Default;
TaskCreationOptions tco = new TaskCreationOptions();
tco = TaskCreationOptions.PreferFairness;
Task task = null;
task = Task.Factory.StartNew(() =>
{
Parallel.Invoke(parOpts, () =>
//while is already in LongRunningMethod() because can not be here
//while (!tokenFor_task.IsCancellationRequested)
//{
LongRunningMethod()
//}
);
}, tokenFor_task.Token, tco, TaskScheduler.Default);
}
private void NeedToUse_MaxDegreeOfParallelism_Method4()
{
CancellationTokenSource tokenFor_task = new CancellationTokenSource();
ParallelOptions parOpts = new ParallelOptions();
//parOpts.CancellationToken = tokenFor_task_tpl_Pair01.Token;
parOpts.MaxDegreeOfParallelism = Environment.ProcessorCount;
//parOpts.TaskScheduler = TaskScheduler.Default;
TaskCreationOptions tco = new TaskCreationOptions();
tco = TaskCreationOptions.PreferFairness;
Task task = null;
Parallel.Invoke(parOpts, () =>
task = Task.Factory.StartNew(() =>
{
while (!tokenFor_task.IsCancellationRequested)
{
LongRunningMethod();
}
}, tokenFor_task.Token, tco, TaskScheduler.Default)
);
}
現在、エラーは発生していません。最初と 2 番目の方法は、使用する必要がある MaxDegreeOfParallelism を考慮していません。Parallel.Invoke を使用しないのが理想ですが、Task.Factory.StartNew に parOpts.MaxDegreeOfParallelism を含めるにはどうすればよいですか?