Can you force Parallel.Invoke to use multiple threads?

前端 未结 2 602
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 23:47

I am using the task parallel library like this in a .aspx page:

 Parallel.Invoke(
                new Action[]
                    {
                                 


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-15 00:05

    Parallel.Invoke will run you methods in parallel unless this is more expensive than running them sequentially, or there are no available threads in the threadpool.This is an optimization, not an issue. Under normal circumstances you shouldn't try to second-guess the framework and just let it do its job.

    You should consider overriding this behavior if you want to invoke some long-running IO-bound methods. Parallel.Invoke uses the default TaskScheduler which uses about as many threads as there are cores (not sure how many) to avoid overloading the CPU. This is not an issue if your actions just wait for some IO or network call to complete.

    You can specify the maximum number of threads using the Parallel.Invoke(ParallelOptions,Action[])]1 override. You can also use the ParallelOptions class to pass a cancellation token or specifiy a custom TaskScheduler, eg one that allows you to use more threads than the default scheduler.

    You can rewrite your code like this:

    Parallel.Invoke(
                new ParallelOptions{MaxDegreeOfParallelism=30},
                new Action[]
                    {
                        () => { users= service.DoAbc(); },
                        () => { products= service.DoDef(); }
                    });
    

    Still, you should not try to modify the default options unless you find an actual performance problem. You may end up oversubscribing your CPU and causing delays or thrashing.

提交回复
热议问题