指定并行LINQ对象任务超时 [英] Specify task timeout in parallel linq to objects

查看:119
本文介绍了指定并行LINQ对象任务超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我想在并行处理的图片列表,但超时。我的老代码,这样做是通过项目分页和使用WaitHandles,但我想使用.NET 4中提供的新并行LINQ或任务的库。



下面的代码片段是工作,我怎么超时补充呢? (超时会为每个任务执行,而不是一个超时要处理的所有项目)

 私人PictureList FetchPictures(列表<图片> ; wallResults)
{
wallResults
.AsParallel()
.WithDegreeOfParallelism(10)
.ForAll(委托(图片p){


解决方案

您可以使用的 WithCancellation() 为:

  VAR CTS =新CancellationTokenSource(超时); 

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

如果你不能使用.NET 4.5,您将无法使用 CancellationTokenSource 的超时接受的构造函数,所以你必须使用定时器手动。


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){

解决方案

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.

这篇关于指定并行LINQ对象任务超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆