Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
ljw1004
Jan 18, 2005

rum

Dirk Pitt posted:

Ahhh, I was using task.run to avoid having to make an async void.

What am I supposed to do if I need to await an asyncronous method in an override void or constructor? I typically make everything async all the way down. This is an issue I am curious about in a framework I have little control over (xamarin).

This is a common problem. It comes from frameworks that expect you to do stuff synchronously even though often you have to do it asynchronously. A typical scenario is that the framework has a void method "LoadSettings" or I guess your "LoadState", which it's willing to execute before the app's main page gets displayed. But obviously it'd be bad app design to DELAY the main page from being displayed while you're loading data off disk or off network.

So what you should do is kick off your async operation in LoadSettings or LoadState or wherever it is. Then return immediately so the outlines of the page can be shown to the user as soon as possible. Later on, you will be able to populate more data into the page once the load has finished.

I don't think you should be doing "Task.Wait" or "Task.Result" to block the main page from displaying until after the long-running load has finished...

code:
class C {
  overrides void LoadState() {
    loadStateTask = LoadStateAsync();
  }
  async Task LoadStateAsync() {
    ... await ...
  }
  Task loadStateTask;
}
After this you have to figure out how to deal with populating the page asynchronously after the data has loaded. There are a bunch of ways. In a XAML app I would write

code:
override async void OnNavigatedTo(...)
  await loadStateTask;
  ... populate the UI
}

Adbot
ADBOT LOVES YOU

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?

Dirk Pitt posted:

Ahhh, I was using task.run to avoid having to make an async void.

What am I supposed to do if I need to await an asyncronous method in an override void or constructor? I typically make everything async all the way down. This is an issue I am curious about in a framework I have little control over (xamarin).

Task is the return type for async methods that would otherwise return void.


C# code:
public async Task ReturnsVoid()
{
    await SomeAsyncMethod();
}

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

kingcrimbud posted:

Task is the return type for async methods that would otherwise return void.


C# code:
public async Task ReturnsVoid()
{
    await SomeAsyncMethod();
}

If you're dealing with a void method that you're overriding, you can't go and change the method signature to Task. That's the problem. You also can't have an async constructor, for obvious reasons.

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?

Ithaqua posted:

If you're dealing with a void method that you're overriding, you can't go and change the method signature to Task. That's the problem. You also can't have an async constructor, for obvious reasons.

You're right, I looked over the changing of the signature part.

Dirk Pitt
Sep 14, 2007

haha yes, this feels good

Toilet Rascal

ljw1004 posted:

This is a common problem. It comes from frameworks that expect you to do stuff synchronously even though often you have to do it asynchronously. A typical scenario is that the framework has a void method "LoadSettings" or I guess your "LoadState", which it's willing to execute before the app's main page gets displayed. But obviously it'd be bad app design to DELAY the main page from being displayed while you're loading data off disk or off network.

So what you should do is kick off your async operation in LoadSettings or LoadState or wherever it is. Then return immediately so the outlines of the page can be shown to the user as soon as possible. Later on, you will be able to populate more data into the page once the load has finished.

I don't think you should be doing "Task.Wait" or "Task.Result" to block the main page from displaying until after the long-running load has finished...

code:

class C {
  overrides void LoadState() {
    loadStateTask = LoadStateAsync();
  }
  async Task LoadStateAsync() {
    ... await ...
  }
  Task loadStateTask;
}

After this you have to figure out how to deal with populating the page asynchronously after the data has loaded. There are a bunch of ways. In a XAML app I would write

code:

override async void OnNavigatedTo(...)
  await loadStateTask;
  ... populate the UI
}

Thank you, so in this instance it appears you are ok with having an async void outside of a top level event handler? Especially if it on a well tested framework like Xamarin?

Ithaqua posted:

If you're dealing with a void method that you're overriding, you can't go and change the method signature to Task. That's the problem. You also can't have an async constructor, for obvious reasons.

Correct, thanks for mentioning this.

raminasi
Jan 25, 2005

a last drink with no ice

Mr Shiny Pants posted:

Rewrote it like this:
code:
let DecodeUrl (request:TogetherRequest) =
    let list1 = Array.map(fun (x:string) -> x.Trim('/'))request.Url.Segments
    let list2 = Array.choose(fun x -> if (String.IsNullOrEmpty(x)) then None else Some(x))list1
    let request = {Method=request.HttpMethod;Url=list2}
    request
Still getting the error.

Error message:

code:
System.AccessViolationException was unhandled
Message: An unhandled exception of type 'System.AccessViolationException' occurred in FSharp.Core.dll
Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Edit:

Rewrote as pointed out:
code:
let DecodeUrl (request:TogetherRequest) =
    let list1 = Array.map(fun (x:string) -> x.Trim('/'))request.Url.Segments
    let list2 = Array.filter(not << String.IsNullOrEmpty)list1
    let request = {Method=request.HttpMethod;Url=list2}
    request
Still getting the accessviolation. Weird huh?

Which line is the exception on? (And why did you eliminate that whitespace? That's a super weird style.)

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Dirk Pitt posted:

Thank you, so in this instance it appears you are ok with having an async void outside of a top level event handler? Especially if it on a well tested framework like Xamarin?


OnNavigatedTo is an event handler.

Mr Shiny Pants
Nov 12, 2012

GrumpyDoctor posted:

Which line is the exception on? (And why did you eliminate that whitespace? That's a super weird style.)

What whitespace? I'll take a look and let you know.

Knyteguy
Jul 6, 2005

YES to love
NO to shirts


Toilet Rascal
Edit nevermind didn't see kingcrimbud's response.

Knyteguy fucked around with this message at 18:02 on Oct 21, 2014

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

This is more of an academic question, but what's up with String.Format("0.00") versus Math.Round? I've got a weight value that I always want to underreport/round down a little bit, so I've been using:
code:
Format(SomeDecimal,"0.0")
As I thought it would just truncate x.xx to x.x without getting all mathematical. Instead it appears to be doing Midpoint Rounding away from zero as demonstrated here:
http://stackoverflow.com/questions/2226081/why-does-net-use-a-rounding-algorithm-in-string-format-that-is-inconsistent-wit

This means that say, 2.77 ends up being 2.8 instead of the 2.7 I want. Is there a consistent way to do this? .ToString("0.#")?

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
You could always cheat: Format(((int)(SomeDecimal * 10))/10, "0.0").

Mr Shiny Pants
Nov 12, 2012
Wow pattern matching is nice.

Matching on a string and the contents of an array just blew my mind. :)

crashdome
Jun 28, 2011

Scaramouche posted:

This is more of an academic question, but what's up with String.Format("0.00") versus Math.Round? I've got a weight value that I always want to underreport/round down a little bit, so I've been using:
code:
Format(SomeDecimal,"0.0")
As I thought it would just truncate x.xx to x.x without getting all mathematical. Instead it appears to be doing Midpoint Rounding away from zero as demonstrated here:
http://stackoverflow.com/questions/2226081/why-does-net-use-a-rounding-algorithm-in-string-format-that-is-inconsistent-wit

This means that say, 2.77 ends up being 2.8 instead of the 2.7 I want. Is there a consistent way to do this? .ToString("0.#")?

The custom numerical formats always round (up? I think?) for display. The difference between Math.Round and the formatter are that Math.Round alters the underlying value and returns it - if it is to be used elsewhere - whereas "0.00" will not return the value.

You are going to want to Math.Truncate your value and use that returned value in your display

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

Bognar posted:

You could always cheat: Format(((int)(SomeDecimal * 10))/10, "0.0").

Yeah, as crashdome says, if I'm going to be messing with multiply/divide I'd just do Math.Truncate(SomeDecimal * 10)/10, which is apparently what I'll have to do. Just seemed weird because "Format" to me implies that no math would be going on. Lesson learned I guess; the whole point of the exercise is that I'm converting from pennyweight, pounds, troy ounces, grains, whatever the supplier provides. Since it involves precious metals I always want to be rounding down instead of up.

Neurion
Jun 3, 2013

The musical fruit
The more you eat
The more you hoot

I've two questions one question.

I'm very familiar with VB .Net, and have written a fair number of applications for my own use with it. I'm also somewhat familiar with C/C++. Would I see any performance benefit from attempting to rewrite some of my applications in C#? I somewhat doubt it, seeing as how both C# and VB compile to CLR, so they'd probably result in similar performance (though worse in the case of C#, owing to my lack of familiarity with it.)

The other question was how to determine if a target process is 32- or 64-bit, but I figured out how to do that with calls to kernel32.dll.

Neurion fucked around with this message at 07:39 on Oct 22, 2014

chippy
Aug 16, 2006

OK I DON'T GET IT
I'm working on a number of reporting widgets for a factory control system that I maintain. They show KPIs in a variety of formats. The boss wants to be able to resize them so he can have them nice and big on large displays in the factory, and he always wants to be able to make them small so he can open lots of them on one screen for his own benefit.

I've got the charts themselves resizing nicely but the labels (not the chart labels, but other text labels on the form) are being a real pain. At the moment I'm having to just fiddle about and find optimum font sizes for different heights and weights of the form, and change them as appropriate by handling the resize event. Does anyone know if there's a less fiddly and soul destroying weight of doing this? Something a bit more automagic?

Gul Banana
Nov 28, 2003

Neurion posted:

I'm very familiar with VB .Net, and have written a fair number of applications for my own use with it. I'm also somewhat familiar with C/C++. Would I see any performance benefit from attempting to rewrite some of my applications in C#? I somewhat doubt it, seeing as how both C# and VB compile to CLR, so they'd probably result in similar performance (though worse in the case of C#, owing to my lack of familiarity with it.)

they're each just as fast for almost all purposes. C# does have the option of using unsafe blocks in which unchecked arithmetic and pointer accesses can be performed, but it's rarely worthwhile.

Neurion
Jun 3, 2013

The musical fruit
The more you eat
The more you hoot

Gul Banana posted:

they're each just as fast for almost all purposes. C# does have the option of using unsafe blocks in which unchecked arithmetic and pointer accesses can be performed, but it's rarely worthwhile.

Yeah, I saw that I could use pointers in unsafe blocks in C#, and as much as I love pointers and pointer arithmetic, I can achieve what I need using an array of bytes and the Marshal.Copy function. Thanks for the confirmation.

kingcrimbud
Mar 1, 2007
Oh, Great. Now what?
What is the proper approach to using FileConfigurationSource with a relative path to a config in another project? The value that works locally does not work once deployed. I believe the config has been set to copy if newer. We've also tried adding the config as a link in the project creating the FileConfigurationSource.

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION
Has anyone here tried using WP.NET (WordPress running under .NET)? The website makes it sound pretty good but they have virtually no concrete information on how it works or how to develop in C# for it or anything.

Gul Banana
Nov 28, 2003

:[ we just got hit by a vb.net compiler bug. turns out that if you have a pair of functions like this:

code:
iterator function foo() as ienumerable(of x)
    yield a
    yield b
end function

iterator function bar() as ienumerable(of x)
    yield c
    yield d
end function
then it can be silently miscompiled as if you had written this:

code:
iterator function foo() as ienumerable(of x)
    yield a
    yield b
    yield c
    yield d
end function

iterator function bar() as ienumerable(of x)
end function
this bug only occurs if the functions are physically adjacent in the code, with no other methods between them. it's fixed in vs2013, which i'm using, but our build server isn't... very very confusing.

Mr Shiny Pants
Nov 12, 2012
Anyone know how to debug a filestream dispose issue?

I have a temp file that is written with FileOptions.DeleteOnClose but it doesn't get removed.

The debugger says my application still has a handle on it, but I don't know why.

Is there any way I can see what I didn't dispose of properly?

nvm I'm a retard. That's what you get staring at code too long.

Mr Shiny Pants fucked around with this message at 12:05 on Oct 23, 2014

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

The Wizard of Poz posted:

Has anyone here tried using WP.NET (WordPress running under .NET)? The website makes it sound pretty good but they have virtually no concrete information on how it works or how to develop in C# for it or anything.

That's weird, other than the original press release there's like literally zero discussion of it. I'm running WP on IIS for a few projects, but it's all php on Windows.

It's looks like it's just the WP code compiled by Phalanger:
http://www.php-compiler.net/

I guess if you wanted you could just get Phalanger and the latest WP and see if it works for yourself, since that's apparently all they're doing.

wwb
Aug 17, 2004

I'd love to see their stats comparing it to wordpress running on linux under apache or nginx -- I'm not sure their speed claims quite ring true.

Scaramouche
Mar 26, 2001

SPACE FACE! SPACE FACE!

I would too actually, wouldn't mind getting rid of php on that machine entirely, mostly for performance reasons. The only customizing we do is CSS/style, though I guess the occasional change to header.php and functions.php would have to be re-compiled in.

ljw1004
Jan 18, 2005

rum

Gul Banana posted:

:[ we just got hit by a vb.net compiler bug. turns out that if you have a pair of iterator functions ... then it can be silently miscompiled as if you had written this:

Gosh! I implemented the iterator+async functions in VB for VS2012 and I never dreamt they could get this goofy. Sorry...


The Wizard of Poz posted:

Has anyone here tried using WP.NET (WordPress running under .NET)? The website makes it sound pretty good but they have virtually no concrete information on how it works or how to develop in C# for it or anything.

Also maybe consider http://www.orchardproject.net/ - I've heard lots of positive comments about it

putin is a cunt
Apr 5, 2007

BOY DO I SURE ENJOY TRASH. THERE'S NOTHING MORE I LOVE THAN TO SIT DOWN IN FRONT OF THE BIG SCREEN AND EAT A BIIIIG STEAMY BOWL OF SHIT. WARNER BROS CAN COME OVER TO MY HOUSE AND ASSFUCK MY MOM WHILE I WATCH AND I WOULD CERTIFY IT FRESH, NO QUESTION

ljw1004 posted:

Also maybe consider http://www.orchardproject.net/ - I've heard lots of positive comments about it

Yep - this is another one that's under very strong consideration. We're currently using Sitefinity and the experience is pretty rocky so far, just approaching the 12 month mark.

Scaramouche posted:

That's weird, other than the original press release there's like literally zero discussion of it. I'm running WP on IIS for a few projects, but it's all php on Windows.

It's looks like it's just the WP code compiled by Phalanger:
http://www.php-compiler.net/

I guess if you wanted you could just get Phalanger and the latest WP and see if it works for yourself, since that's apparently all they're doing.

Yeah gently caress it, I'll just dive in and take a look.

ljw1004
Jan 18, 2005

rum
On two of the new features we're planning for C#6 and VB14, we've been rethinking about how they work. I'm posting here in case anyone has thoughts on the changes...

String interpolation - https://roslyn.codeplex.com/discussions/570292
This aims to be an easier way than String.Format to build up strings, including programmatic API strings like urls, filepaths, ...
code:
// Changed to use $"...{expr}..." rather than "...\{expr}...".
var x = $"hello {person.name} you are {person.age} years old"

// Changed to allow arbitrary format strings rather than just limited ones.
var x = $"you are {person.height:0.00} tall"

// Changed to allow access invariant culture.
IFormattable x = $"you are {person.height:0.00} tall";
var invstring = f1.ToString(null, CultureInfo.InvariantCulture);
NameOf operator - https://roslyn.codeplex.com/discussions/570551
This aims to be used in places like ArgumentNullException, or PropertyChangedEventArgs, or DependencyProperty.Register, where you need to pass the string name of a programmatic element but if your code is full of string literals then it's too easy to make mistakes.
code:
// Changed to allow certain expressions in its argument
Console.WriteLine(nameof(this.p)); // returns "p"

// Changed to disallow certain types
var s = nameof(List<>.Length); // now an error

// Changed to allow only a sequence of dot-qualified identifiers
var s = nameof(StrongBox<string>.Value.Length); // returns "Length"
var s = nameof(((StrongBox<string>)(null).Value); // error not allowed casts

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

ljw1004 posted:

NameOf operator - https://roslyn.codeplex.com/discussions/570551
This aims to be used in places like ArgumentNullException, or PropertyChangedEventArgs, or DependencyProperty.Register, where you need to pass the string name of a programmatic element but if your code is full of string literals then it's too easy to make mistakes.
code:
// Changed to allow certain expressions in its argument
Console.WriteLine(nameof(this.p)); // returns "p"

// Changed to disallow certain types
var s = nameof(List<>.Length); // now an error

// Changed to allow only a sequence of dot-qualified identifiers
var s = nameof(StrongBox<string>.Value.Length); // returns "Length"
var s = nameof(((StrongBox<string>)(null).Value); // error not allowed casts

I like the nameof operator, since in every project where I use PropertyChanged, I already use something like this to avoid using magic strings all over the place (with more safety checks):

C# code:
protected void RaisePropertyChanged<T>(Expression<Func<T>> property)
{
    var propName = ((PropertyInfo)((MemberExpression)expression.Body).Member).Name;
    OnPropertyChanged(propName);
}

// calling code
public string SomeProperty
{
    get { return _someProperty; }
    set { _someProperty = value; RaisePropertyChanged(() => SomeProperty); }
}
I'd love to have a built in way to do this.

Maybe I missed it while reading the post on codeplex, but is there a succinct write-up of the changes between spec versions?

Bognar fucked around with this message at 15:21 on Oct 24, 2014

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy

ljw1004 posted:

NameOf operator - https://roslyn.codeplex.com/discussions/570551
This aims to be used in places like ArgumentNullException, or PropertyChangedEventArgs, or DependencyProperty.Register, where you need to pass the string name of a programmatic element but if your code is full of string literals then it's too easy to make mistakes.

My coworker brought up the possibility of nameof returning a MemberInfo or a special struct that cannot be instantiated elsewhere instead of returning a string. That way, if you were building an API that needed information about methods, you could build it with MemberInfo or the special struct so that you guarantee the method being passed in exists.

Maybe the struct could implicitly cast to both string and MemberInfo to make it easier to use. The nameof operator is a bit of a band-aid around previous .NET APIs that all rely on strings, but with this language feature we could make it easier to avoid that in the future.

Bognar
Aug 4, 2011

I am the queen of France
Hot Rope Guy
Sorry for the triple post.

We're getting ready to do a small project that involves executing a lot of operations that each wait on I/O bound work, perform CPU bound work, followed waiting on more I/O bound work. Performance will matter. This question is two parts.

One:
Is there any kind of .NET built-in "buffer" that will handle throttled pre-loading of I/O bound operations? For example, lets say I want to download 10000 large files from the internet and process them in a single thread. I don't want to download each file individually before processing it, for obvious reasons. However, I also don't want to start 10000 tasks to download the files at once, for more obvious reasons. What I would like is to have 8-10 of them downloaded and buffered, and kick off more download tasks as the buffered number drops. The API I have in mind is something like this:

C# code:
var bufferedCollection = new BufferedTaskCollection(GetDownloadTasks());
foreach(var task in bufferedCollection)
{
    var download = await task;
    // CPU heavy processing
}
Is there anything in the .NET library that already exists like this?

Two:
Is the above even necessary? Am I better off just writing the whole operation as a single method (await IO, process, await IO) and shoving them all off on the thread pool?

rarbatrol
Apr 17, 2011

Hurt//maim//kill.

Bognar posted:

Sorry for the triple post.

We're getting ready to do a small project that involves executing a lot of operations that each wait on I/O bound work, perform CPU bound work, followed waiting on more I/O bound work. Performance will matter. This question is two parts.

One:
Is there any kind of .NET built-in "buffer" that will handle throttled pre-loading of I/O bound operations? For example, lets say I want to download 10000 large files from the internet and process them in a single thread. I don't want to download each file individually before processing it, for obvious reasons. However, I also don't want to start 10000 tasks to download the files at once, for more obvious reasons. What I would like is to have 8-10 of them downloaded and buffered, and kick off more download tasks as the buffered number drops. The API I have in mind is something like this:

C# code:
var bufferedCollection = new BufferedTaskCollection(GetDownloadTasks());
foreach(var task in bufferedCollection)
{
    var download = await task;
    // CPU heavy processing
}
Is there anything in the .NET library that already exists like this?

Two:
Is the above even necessary? Am I better off just writing the whole operation as a single method (await IO, process, await IO) and shoving them all off on the thread pool?

You might be able to do something like a parallel foreach loop: http://msdn.microsoft.com/en-us/library/ff963552.aspx. You can optionally specify the degree of parallelism, too (I think it defaults to the number of cores?).

Edit: I'm guessing the bottleneck here is going to be network IO, so I don't know how much you can feasibly optimize the performance beyond saturating the connection.

rarbatrol fucked around with this message at 03:48 on Oct 25, 2014

Destroyenator
Dec 27, 2004

Don't ask me lady, I live in beer

ljw1004 posted:

NameOf operator - https://roslyn.codeplex.com/discussions/570551
This aims to be used in places like ArgumentNullException, or PropertyChangedEventArgs, or DependencyProperty.Register, where you need to pass the string name of a programmatic element but if your code is full of string literals then it's too easy to make mistakes.
code:
// Changed to allow certain expressions in its argument
Console.WriteLine(nameof(this.p)); // returns "p"

// Changed to disallow certain types
var s = nameof(List<>.Length); // now an error

// Changed to allow only a sequence of dot-qualified identifiers
var s = nameof(StrongBox<string>.Value.Length); // returns "Length"
var s = nameof(((StrongBox<string>)(null).Value); // error not allowed casts
This looks cool and it seems like you've though out all the main use cases. I'm not clear though if you're able to do chained member access on types?
eg. nameof(SomeClass.Property.InnerPropertyName)

I'd probably use them when constructing web forms that post back different view models.

Mr Shiny Pants
Nov 12, 2012
F# really is a nice language. The whitespace stuff can be loving annoying but I am getting the hang of it.

One thing I learned, when VS says you are good to go with F# code, it usually works as intended. Which is pretty awesome.

Another thing: The REPL is awesome, testing some functions by just selecting them and selecting "Run in interactive" is pretty awesome.

I built an upload function and instead of creating another project to test it, i just pasted the function in the FSI ran my program and executed the function. Nice!

Mr Shiny Pants fucked around with this message at 22:51 on Oct 25, 2014

brap
Aug 23, 2004

Grimey Drawer
I wish the REPL for F# was as good as one for a scripting language or even as good as the immediate window for C#. I found it to be a struggle.

brap fucked around with this message at 03:29 on Oct 26, 2014

evilfunkyogi
Jun 27, 2005
:effort:

Bognar posted:

I like the nameof operator, since in every project where I use PropertyChanged, I already use something like this to avoid using magic strings all over the place (with more safety checks):

C# code:
protected void RaisePropertyChanged<T>(Expression<Func<T>> property)
{
    var propName = ((PropertyInfo)((MemberExpression)expression.Body).Member).Name;
    OnPropertyChanged(propName);
}

// calling code
public string SomeProperty
{
    get { return _someProperty; }
    set { _someProperty = value; RaisePropertyChanged(() => SomeProperty); }
}
I'd love to have a built in way to do this.

Maybe I missed it while reading the post on codeplex, but is there a succinct write-up of the changes between spec versions?

You can also do this using 4.5's CallerMemberName attribute, which is a bit cleaner - see this blog post.

evilfunkyogi fucked around with this message at 01:05 on Oct 26, 2014

Mr Shiny Pants
Nov 12, 2012

fleshweasel posted:

I wish the REPL for F# was as good as one for a scripting language or even as good as the immediate window for C#. I found it to be a struggle.

No command completion is a pain, true. I just cut and paste the commands form the editor.

Paul MaudDib
May 3, 2006

TEAM NVIDIA:
FORUM POLICE
Dumb question, I'm working through Project Euler and I figured I'd get cute and parallelize one of my inner loops to speed things up. However, I must be doing something wrong because the parallel version is significantly slower - by like a factor of 6.

Single-threaded:
code:
for (int p = 0; p < primesFound.Count; p++)
                {
                    int myPrime = primesFound[p];

                    //if a known prime divides i evenly, then i is NOT a new prime
                    if (i % myPrime == 0)
                    {
                        isPrime = false;
                        break;
                    }
                }
Multi-threaded:
code:
Parallel.For(0, primesFound.Count, (p, loopState) =>
                {
                    int myPrime = primesFound[p];
                
                    //if a known prime divides i evenly, then i is NOT a new prime
                    if (i % myPrime == 0)
                    {
                        isPrime = false;
                        loopState.Break();
                    }
                });
Parallel.ForEach has similar results. What's the explanation here?

e: I think I'm probably doing too little work in the loop, plus the fact that the small primes are very frequently encountered and cause an early break, which means I'm getting a lot of launch/join overhead too.

Paul MaudDib fucked around with this message at 17:59 on Oct 27, 2014

Alien Arcana
Feb 14, 2012

You're related to soup, Admiral.
Hey thread, I have a question about generics.

Suppose I am in a generic method "LoadValue<T>", and by use of typeof() I have determined that T is a List<>. That is to say, it is a List<U> for some type U. I would like to call another generic method "ReadList<U>" with that type U. Is there any "clean" way to do this?

Basically this is what I want to do:

code:
object LoadValue<T>()
{
  // ...

  if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List<>)))
  {
    return ReadList<U>(); // where U is defined by typeof(T) == typeof(List<U>)
  }

  // ...
}
Currently the best way I have to do this is:

code:
object LoadValue<T>()
{
  // ...

  if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List<>)))
  {
    return typeof(this).GetMethod("ReadList").MakeGeneric(typeof(T).GetGenericArguments()).Invoke(this, new object[0]);
  }

  // ...
}
which is hard to read, somewhat slower, and also prone to human error since Visual Studio can't check that the function I'm referencing actually exists.

Is there a better way to do this?

(any possible improvements to that if-clause that would also be appreciated)

Adbot
ADBOT LOVES YOU

New Yorp New Yorp
Jul 18, 2003

Only in Kenya.
Pillbug

Paul MaudDib posted:

e: I think I'm probably doing too little work in the loop, plus the fact that the small primes are very frequently encountered and cause an early break, which means I'm getting a lot of launch/join overhead too.

Yup. Parallelization has a ton of overhead, which is why you should only launch new threads when you're doing long-running, CPU-bound work.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply