0

My qestion is about the result of combination PLINQ and yield keyword. What will happen if i write like so:

//Some stuff here
foreach (var x in collection.AsParallel())
{
    yield return new CustomObject
    {
        property1 = //Large calculations here
        property2 = x.Name
        //... etc.
    };
}

What do I really want? I want to initialize objects in different threads but return them when some of them needs.
Thanks in advance!

user3818229
  • 1,537
  • 2
  • 21
  • 46

1 Answers1

3

AsParallel just enables the use of parallel versions of the LINQ operations. It doesn't actually do anything in and of itself.

So your code, outside of a tiny bit of extra overhead, is functionally no different from you having omitted AsParallel entirely.

If you want to actually be able to perform the construction of the CustomObject instances in parallel, and you want to use PLINQ to do it (there are of course any number of other tools you can use to create objects in parallel), then you'll want to use Select to transform a sequence of one type into a sequence of another type, rather than using your own custom iterator block.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Thank you for explaining! Let me ask connected question with this library. If I do so: .AsParallel().Select(x => {var t = _db.//some work with db context; return new ...}) do I have any problem with connections? I mean "second thread start his job before the first one close execution in the same context"? – user3818229 Apr 19 '17 at 17:36
  • 1
    @user3818229 I would highly doubt that any db provider would support that, but it would of course depend on the provider. – Servy Apr 19 '17 at 17:43