Specify task timeout in parallel linq to objects

一笑奈何 提交于 2020-01-13 03:48:24

问题


I have a list of Pictures that I want to process in parallel, but with a timeout. My old code did this by paging through the items and using WaitHandles, but I want to use the new Parallel Linq or Tasks library available in .Net 4.

The following snippet is working, how do I add a timeout to it? (Timeout would be for each task executing, not a timeout for all items to be processed)

   private PictureList FetchPictures(List<Picture> wallResults) 
   {                
            wallResults
                .AsParallel()
                .WithDegreeOfParallelism(10)
                .ForAll(delegate(Picture p){

回答1:


You can use WithCancellation() for that:

var cts = new CancellationTokenSource(timeout);

wallResults
    .AsParallel()
    .WithCancellation(cts.Token)
    .WithDegreeOfParallelism(10)
    .ForAll(p => { …

If you can't use .Net 4.5, you won't be able to use timeout-accepting constructor of CancellationTokenSource, so you'll have to use Timer manually.



来源:https://stackoverflow.com/questions/18158360/specify-task-timeout-in-parallel-linq-to-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!