请建议正确和有效使用 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)
);
}
目前我没有收到任何错误。第一种和第二种方法没有考虑我需要使用的 MaxDegreeOfParallelism。理想情况下,我不会使用 Parallel.Invoke,但如何在 Task.Factory.StartNew 中包含 parOpts.MaxDegreeOfParallelism?