Specify task timeout in parallel linq to objects

2019-04-09 11:26发布

问题:

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.