سؤال

ReSharper refactored a foreach loop I had to something like this. I wanted to spawn a bunch of threads via a delegate's BeginInvoke with different parameters, stored in a list, and store the IAsyncResults in a collection:

var asyncResults = mylist.Select(x => myDelegate.BeginInvoke(x, null, null));

My instinctive reaction is that this is not a good practice. BeginInvoke is causing a side effect of a new thread being spawned, and functions passed to Select should not cause side effects.

Or maybe it's ok, because I'm not altering anything in the calling thread?

هل كانت مفيدة؟

المحلول

I think it's hard to tell whether this is a good practice or not, it depends on how are you using it.

But the important thing to remember when using LINQ like this is that Select() (and many other LINQ methods) doesn't actually iterate over the collection and execute your code. That happens only when you iterate over the resulting collection, usually using foreach or ToArray().

نصائح أخرى

That should be fine. Creating a new thread isn't really a side affect. You're not modifying any values. BeginInvoke is called and you're storing the resulting IAsyncResults.

You will have to keep in mind, though, that nothing is going to block. You'll have to manage the synchronization of everything yourself.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top