Set task timeout in parallel linq for objects

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

The following snippet works, how can I add a timeout to it? (A timeout will be performed for each task, not a timeout for all processed items)

private PictureList FetchPictures(List<Picture> wallResults) { wallResults .AsParallel() .WithDegreeOfParallelism(10) .ForAll(delegate(Picture p){ 
+4
source share
1 answer

You can use WithCancellation() to do this:

 var cts = new CancellationTokenSource(timeout); wallResults .AsParallel() .WithCancellation(cts.Token) .WithDegreeOfParallelism(10) .ForAll(p => { … 

If you cannot use .Net 4.5, you will not be able to use the CancellationTokenSource time constructor, so you will have to use Timer manually.

+2
source

Source: https://habr.com/ru/post/1496275/


All Articles