简体   繁体   English

有条件的并行

[英]Parallel.ForEach with conditions

I have list of objects. 我有对象清单。 Object is instance of class. 对象是类的实例。 Inside each object is property that hold some value: 每个对象内部都有一些值的属性:

List<SomeClassTask> lstSomeTaskList = new List<SomeClassTask>();

for (int i=0; i<5; i++)
{
     SomeClassTask tsk = new SomeClassTask();
     Thread.Sleep(500);
     tsk.SomeProperty = new Random().Next(1, 11);

     lstSomeTaskList.Add(tsk);
}

The next step is to run parallel task for each object 下一步是为每个对象运行并行任务

Parallel.ForEach(lstSomeTaskList, task => task.StartProcessing(task.SomeProperty));

I want to start only specific tasks like task which has value 1 (SomeProperty = 1). 我只想启动特定任务,例如具有值1(SomeProperty = 1)的任务。

This is class: 这是课程:

class SomeClassTask
{
    public int SomeProperty { get; set; }
    public void StartProcessing(int maxRange)
    {
        int rnd = new Random().Next(1, maxRange);
        Thread.Sleep(1000);
        Console.WriteLine("Parallel task -> radnom created value: " + rnd);
    }
}

Is it possible inside 里面可能吗

Parallel.ForEach Parallel.ForEach

put some conditions to check some object properties? 放一些条件检查一些对象属性?

Parallel.ForEach Gets a IEnummerable as Source, so you just need to filter your list object and feed it to the ForEach, something like: Parallel.ForEach获取IEnummerable作为源,因此您只需要过滤列表对象并将其提供给ForEach,例如:

SomeClassTask a = new SomeClassTask { SomeProperty = 1 };
SomeClassTask b = new SomeClassTask { SomeProperty = 2 };

List<SomeClassTask> lstSomeTaskList = new List<SomeClassTask> { a, b };

Parallel.ForEach(lstSomeTaskList.Where(task => task.SomeProperty == 1),
task => task.StartProcessing(task.SomeProperty));

Edit 编辑
As the comments has pointed out already, you should check this -> https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomness/ 正如评论已经指出的那样,您应该检查一下-> https://codeblog.jonskeet.uk/2009/11/04/revisiting-randomness/

You should use Microsoft's Reactive Framework (aka Rx) - NuGet System.Reactive and add using System.Reactive.Linq; 您应该使用Microsoft的Reactive Framework(aka Rx)-NuGet System.Reactiveusing System.Reactive.Linq;添加using System.Reactive.Linq; - then you can do this: -那么您可以执行以下操作:

IObservable<SomeClassTask> query =
    from i in Observable.Range(0, 5)
    let tsk = new SomeClassTask() { SomeProperty = _random.Next(1, 11) }
    where tsk.SomeProperty == 1
    from u in Observable.Start(() => tsk.StartProcessing(tsk.SomeProperty))
    select tsk;

IDisposable subscription = query.Subscribe();

Now, if you want all of the results when the query has finished then do this: 现在,如果要在查询完成后获得所有结果,请执行以下操作:

IDisposable subscription =
    query
        .ToList()
        .Subscribe(list => { /* use `list` here */ });

If you need to finish process before it completes then just do subscription.Dispose(); 如果您需要在完成之前完成流程,则只需进行subscription.Dispose(); .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM