How to execute function on Parallel.ForEach? - c#

I'm trying to:
Parallel.ForEach(listOfNames, name => DoSometingWithName(name));
while VS asks me to convert method to group, while i can't since this method is used from other places as well. So i don't want to copy paste the code around.
Is there a way to ?

Caused by ReSharper thus guys without it never seen this message. I thought it was compiler error.
Elegant work around would be:
Parallel.ForEach(listOfNames, DoSometingWithName);
Not sure it is more readable though.

Not sure what you mean, but did you search this syntax?
Parallel.ForEach(listOfNames, name =>
{
//Place your code here.
DoSometingWithName(name);
});

Related

EnsureBindingContextSet method missing from the MvxAppCompatDialogFragment class

I am trying to create a custom dialog using the MvxAppCompatDialogFragment and AlertDialog.Builder classes. I've looked through every bit of example that I could find on the internet but I'm stuck on this one part. Every single one of those working samples that I've found used the base.EnsureBindingContextSet method inside the overridden OnCreateDialog method. But every time I use that method, the compiler keeps giving me this error:
'MvxAppCompatDialogFragment<MyViewModel>' does not contain a definition for 'EnsureBindingContextSet'
So I tried to look for others who have this problem. But no matter how hard I searched, no matter the keywords that I use, I really can't find anyone who has this same problem. I hope someone can help me with this problem.
The version of MvvmCross that I use is 6.0.1. Here is the part of my code which gives me problems, in case it might help. It's still quite empty since it won't work on my first test.
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
base.EnsureBindingContextSet(savedInstanceState);
var view = this.BindingInflate(Resource.Layout.DurationDialogFragment, null);
var builder = new AlertDialog.Builder(Activity);
builder
.SetView(view)
.SetPositiveButton("Confirm", (s, e) => { })
.SetNegativeButton("Cancel", (s, e) => { ViewModel.CloseCommand.Execute(); });
var dialog = builder.Create();
dialog.SetCanceledOnTouchOutside(false);
return dialog;
}
Ok, I've made it work. I've found the source code on how the EnsureBindingContextSet was implemented and used it instead.
I've actually found the latest source code from Martin's github page and it looks like the EnsureBindingContextSet method is gone. Here's the link if you want to check:
https://github.com/MvvmCross/MvvmCross/blob/develop/MvvmCross.Android.Support/V7.AppCompat/MvxAppCompatDialogFragment.cs
So what I did was to type:
this.EnsureBindingContextIsSet();
and used intellisense to find the proper using statement to use, which is:
using MvvmCross.Droid.Support.V4;
Also using intellisense, I think that the problem is that the new EnsureBindingContextIsSet extension method does not accept a Bundle object as a parameter anymore which resulted in the method's removal.
Seeing as I can't find any trace of this problem in the internet, I hope that this will help somebody who comes into this exact problem in the future.

C# Comparing Values from dynamic's

Today i tried an old project, in my company and got an error which makes me curious. The issue line looks something like this:
if((dynamic)com_list.GetIntValue() != (dynamic)container.GetEnumValue())
The exception shows clearly that you can't compare Int32 with an Enum.
But i wonder, could this have ever worked, in some circumstance?
Are there changes in the dynamic Keyword which don't allow this anymore?
BTW, he also build this in the code like this:
if((dynamic)com_list.GetIntValue() != (dynamic)container.GetBooleanValue())
I'm still confused, why somebody would put this kind of comparing into productiv code.
No. The dynamic specification hasn't changed and I am pretty sure the evaluation in the compiler of such a trivial comparison didn't change overnight in one release to another. Most likely that code never worked.
Without additional cast from enum to int (or the other way around) it won't work.

How do I know if certain extensions methods 'mutate' the object or not?

Feel free to edit 'mutate' from the title if it's a poor choice of wording.
My question is, relatively, simple.
Take the following example:
myCollection.OrderBy(o => o);
How do I know whether OrderBy will/will not order myCollection or whether an assignment (following) is necessary:
myCollection = myCollection.OrderBy(o => o);
Is it a case of having to build it and check every time I encounter an extension I'm unfamiliar with?
Please note: I'm not asking whether this will or will not affect myCollection, I already know the answer to that from using it hundreds of times previous, I'm asking how I'd know.
You can't tell from just the signature.
The best you can do is to investigate the actual code, for example by looking at the .NET Reference Source. Another thing you could do is check the return type. If it is the same as the one it's being called on, it probably doesn't change it, it most likely returns a new instance. Is it a void, then it probably does change something inside.
For your specific case for example, OrderBy: no. See here. It 'just' returns a new OrderedEnumerable.
You can check for the Pure attribute in the class decoration as Steven Liekens said. But in its absence, the only way to know for sure is by:
Experimenting: for example, get an instance of the class and serialize it. Use the method and then serialize it. Compare the results. May not be accurate every time.
Reverse engineering the method: and I hope you have the source code. If you don't, you can use reflection. This will require some judgement if the method is somewhat complex, but this complexity here is subjective.
Reading the docs and trusting them - if the doc is present. This is the sensible thing to do with the .NET Framework types, and an exercize of faith otherwise.
One way is to find out if the method or its class is marked as [Pure]. Pure code does not modify input values.

Get out of a void method?

I have this method (modified code) :
public static void PublishXmlForCustomTypes(MyOwnClass DefaultOutputInformation)
{
if (DefaultOutputInformation != null)
{
///lot of code
}
}
and my whole code was inside the if statement and after thinking about it, I changed to this :
public static void PublishXmlForCustomTypes(MyOwnClass DefaultOutputInformation)
{
if (DefaultOutputInformation == null)
{
return;
}
///lot of code
}
As far as I tested it, it seems to be strictly equivalent but is that really the case ?
I mean, the "return" statement get us out of the method right ?
This is strictly equivalent and the second version is the way to go :)
Yes, that's absolutely fine.
Some people dogmatically stick to "one exit point per method" - which was appropriate when it was relatively tricky to make sure you always did the right amount of clean-up at the end of a function in C, for example... but it's not really necessary in C#.
Personally I think it's appropriate to return as soon as you know that you've done all the work you really want to in a method. Use try/finally or using statements to perform any extra "clean up however I exit" work.
yes return gets you out of the method; if you have a finally block and you call return from the try block, the finally block is executed anyway.
Yes, the return statement ends the method.
Yes, the return will exit you out of the code. It's generally good practice as the very first step in a function to verify that the parameters that were passed in are what you think they are and exit (via the return or throwing an exception) so that you don't do any unnecessary processing only to have to abort later in the function.
Yes, your assumptions is correct.
For some background, learn about duality.
Yes, it is exactly the same, you can read the MSDN documentation about the keyword return to fully understand how it works : http://msdn.microsoft.com/en-us/library/1h3swy84.aspx
As to decide which way is better : both are good, but the second version makes it more readable because then your whole code isn't inside an if block. This way, you can see what the condition does really easily instead of reading the whole code of the method.
Indeed the return gets you out of the method, so it is equivalent to the first way you used. Which way is better depends on your code, although generally I would prefer the second version.
Looking at the revised code, the second one is the way to go. While being functionally equivalent, think about the case where you passed in 4 different variables to a function that you want to check. Instead of having a do a nasty 4 level if statement with {'s everywhere, the second method allows you to clean up the appearance of the code and not add unnecessary levels of brackets. If you're writing in C/C++, you can even make this a macro such as VERYIFY_NOT_NULL(x) and make the code nice and neat.
Readable/maintainable code trumps nano-seconds of performance 99% of the time.

Understanding a line of example-code

I'm trying to modify this example to my needs, but one line in particular has me stumped. The line ((Action<List<MessageInfo>>)parm)(msgs); in the chatserver makes absolutely no sense to me. I can see that it typecasts (msgs) to the type ((Action<List<MessageInfo>>)parm);, but it doesn't seem to do anything at all.
I hope that someone can help me understand this, as I have a feeling it one of the last pieces I'm missing of this puzzle...
Kind regards.
They are casting a delegate, then invoking it with msgs.
This bit:
((Action<List<MessageInfo>>)parm);
Casts the delegate. Then it invokes the delegate with msgs.
Breaking it down a bit:
Action<List<MessageInfo>> del = ((Action<List<MessageInfo>>)parm);
del(msgs);
The author just chose to collapse all of that into one line.
The line
((Action<List<MessageInfo>>)parm)(msgs)
is not a simple cast, it's a cast followed by an invocation of the method. Basically it does this:
Action<List<MessageInfo>> action = (Action<List<MessageInfo>>)parm;
action(msgs);
What they are saying is:
Consider that:
parm is an Action
that takes as a parameter a List of <MessageInfo>s
and since Actions are executable, execute it,
passing msgs as a parameter.

Categories

Resources