• 0

Reduce .NET app RAM usage


Question

Recommended Posts

  • 0

You should leave the .NET runtime do the job. It will reduce the working sets automatically when memory runs out globally. I don't know why everyone is so obsessed with the memory column on taskman or perfmon with .NET apps. That counter is not representative for the .NET applications memory usage.

Other than that it will require you to import a function call from ntdll.dll or something. Winston and bangbang23 can tell you exactly how.

  • 0

Ahh gees let me reiterate myself for the 500000000 time, but it's alright, you see the .NET Framework, does the memory allocation, what the framework does is, when your system has alot of memory free, say for example you have 512 megs of RAM and use up only 100 then your app with just one form with nothing probably uses about 25 megs, this is primarily because the more RAM you have the more .NET apps reserves for itself, i duno the real reason why it does this it was so confusing listening to the architect guy talk in germanglish lol... but yeah, so say for example if your system had 128 megs of ram and you got 28 megs spare, then your .net app will only make out about 300k - 800k, this is the single form that has nothing on it.

Let's just say what you see in the task manager is probably deceiving, theoretically the application just runs at a very small amount of memory but what's shown for the memory is how much the application has allocated for itself, as soon as the system runs low on memory the .net app will decrease in memory usage, some computer illiterate people might look at the task manager and sh*t their pants seeing your app using so much, so below is the fix which will practically just refresh the task manager so that it displays the memory that's REALLY in use and remove the memory that's spare

so you can come to a conclusion to say what's shown in task manager is basically the representation of:

memory actually being used + additional memory reserved for the program = task manager display

applying of the following function:

? ?
Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal hProcess As IntPtr, ByVal dwMinimumWorkingSetSize As Int32, ByVal dwMaximumWorkingSetSize As Int32) As Int32
 ? ?'Call the Kernel API Set process memory size

Public Function SaveMemory() As Int32

 ? ? ? ?Return SetProcessWorkingSetSize(Diagnostics.Process.GetCurrentProcess.Handle, -1, -1)

 ? ?End Function

'Call the function in the appropriate events, i.e. form Activated, Form Deactivated, which a friend of mine recommeneded me doing

SaveMemory()[b]displays only memory actually consumed by app[/b]by app

I hope this has cleared it up a bit, and could some Mod just sticky this, it's been asked alot!

Cheers

  • 0

Note, however, that there are side effects to using SetProcessWorkingSetSize. If you call that API regularly and the Framework needs to reduce the working size of the app for some reason, the app will throw an OutOfMemoryException, whether the system is actually out of memory or not.

And, as Winston said, that API is just a convenient illusion for people with a gigabyte of RAM who still feel they need to guard every byte jealously. It doesn't actually accomplish anything.

--

Danny Smurf

  • 0

i've also found that, while most of my apps run at 20-25Mb while in use, if i let them sit there long enough and watch the task manager, they'll go down as low as about 500kb until i start using them again.

Really makes it look like some impressive memory management :)

  • 0
  nowimnothing said:
i've also found that, while most of my apps run at 20-25Mb while in use, if i let them sit there long enough and watch the task manager, they'll go down as low as about 500kb until i start using them again.

Really makes it look like some impressive memory management :)

trust me, release the app and you'll get alot of user complaining. It didn't bother me, I had my app at 15mb mem usage, but people kept complaining so I had to use the trick above.

  • 0
  session? said:
Private Declare Function SetProcessWorkingSetSize Lib "kernel32.dll" (ByVal hProcess As IntPtr, ByVal dwMinimumWorkingSetSize As Int32, ByVal dwMaximumWorkingSetSize As Int32) As Int32
  weenur said:
[DllImport("kernel32.dll")]

public extern static bool SetWorkingProcessSetSize( IntPtr hProcess, int min, int max );

Returns Int32, not bool...

  • 0
  bangbang023 said:
trust me, release the app and you'll get alot of user complaining. It didn't bother me, I had my app at 15mb mem usage, but people kept complaining so I had to use the trick above.

If I'm ever going to release one of my apps into public, I will make sure that it has a dialog that shows up on first run that explains them CLEARLY how .NETs memory management works, including checkbox to agree not to complain! Better way than ****ing up an applications performance and stability.

  • 0
  frogg said:
  weenur said:
[DllImport("kernel32.dll")]

public extern static bool SetWorkingProcessSetSize( IntPtr hProcess, int min, int max );

Returns Int32, not bool...

the C declaration of SetProcessWorkingSetSize:

BOOL SetProcessWorkingSetSize( HANDLE hProcess, SIZE_T dwMinimumWorkingSetSize, SIZE_T dwMaximumWorkingSetSize)

You can use bool for BOOL in interop.

I inadvertently swapped Process with Working. That I will admit to being incorrect on. :D

  • 0
  bangbang023 said:
  nowimnothing said:
i've also found that, while most of my apps run at 20-25Mb while in use, if i let them sit there long enough and watch the task manager, they'll go down as low as about 500kb until i start using them again.

Really makes it look like some impressive memory management  :)

trust me, release the app and you'll get alot of user complaining. It didn't bother me, I had my app at 15mb mem usage, but people kept complaining so I had to use the trick above.

I have released the app (its not public stuff, its for internal stuff in my company) and noone cares - i don't think they'd ever notice.

If people are just going on whats showing up in task manager then, well, a) they don't know what they're talking about, and b) why are they staring at task manager anyway?

  • 0
  nowimnothing said:
  bangbang023 said:
  nowimnothing said:
i've also found that, while most of my apps run at 20-25Mb while in use, if i let them sit there long enough and watch the task manager, they'll go down as low as about 500kb until i start using them again.

Really makes it look like some impressive memory management  :)

trust me, release the app and you'll get alot of user complaining. It didn't bother me, I had my app at 15mb mem usage, but people kept complaining so I had to use the trick above.

I have released the app (its not public stuff, its for internal stuff in my company) and noone cares - i don't think they'd ever notice.

If people are just going on whats showing up in task manager then, well, a) they don't know what they're talking about, and b) why are they staring at task manager anyway?

I'm not saying those people are right, but I have had users complain because "it's a sticky note program and shouldn't be using 15mb of RAM." I basically had to do it or be faced with losing users. I don't make money off my app, but I still don't want to lose users.

Tom: First off, it's nice having a somewhat normal, non-fighting discussion lol. Second, I have not had any problems with stability or performance with my app.

  • 0
  bangbang023 said:
  nowimnothing said:
  bangbang023 said:
  nowimnothing said:
i've also found that, while most of my apps run at 20-25Mb while in use, if i let them sit there long enough and watch the task manager, they'll go down as low as about 500kb until i start using them again.

Really makes it look like some impressive memory management?:))

trust me, release the app and you'll get alot of user complaining. It didn't bother me, I had my app at 15mb mem usage, but people kept complaining so I had to use the trick above.

I have released the app (its not public stuff, its for internal stuff in my company) and noone cares - i don't think they'd ever notice.

If people are just going on whats showing up in task manager then, well, a) they don't know what they're talking about, and b) why are they staring at task manager anyway?

I'm not saying those people are right, but I have had users complain because "it's a sticky note program and shouldn't be using 15mb of RAM." I basically had to do it or be faced with losing users. I don't make money off my app, but I still don't want to lose users.

Tom: First off, it's nice having a somewhat normal, non-fighting discussion lol. Second, I have not had any problems with stability or performance with my app.

You'll understand that it may have adverse effects which is unpredictable at times, once again a friend of mine taught me programming, and he has brought me up the right way in thinking, and bangbang i hope you begin to take account for your applications performance, not criticising you much but like i always stressed to u on MSN you shouldnt care about if the thing can be implemented, it should be done in a way that it wont drastically effect performance on ur application, which i did back then wen i designed my app because i had a time constraint as it was a assignment and i needed to get it over and done with, but once i finish my exams im gonna learn .net from the ground up.

  • 0
  Winston said:
You'll understand that it may have adverse effects which is unpredictable at times, once again a friend of mine taught me programming, and he has brought me up the right way in thinking, and bangbang i hope you begin to take account for your applications performance, not criticising you much but like i always stressed to u on MSN you shouldnt care about if the thing can be implemented, it should be done in a way that it wont drastically effect performance on ur application, which i did back then wen i designed my app because i had a time constraint as it was a assignment and i needed to get it over and done with, but once i finish my exams im gonna learn .net from the ground up.

I've told you a million times before, I get the basic code layed out then I worry about performce. It can't run well if it don't run at all. My code is definitely not the best, but neither is yours or anyone else's here, cause otherwise we'd be very rich, but my code is descent (lacking comments but not a problem for me.) Anything that works on my program works well and does not slow down the program. I wouldn't include a "feature" if it slowed down the proggy.

Either way, this is off topic. You don't like my code? So be it. I honestly think you want it done your way or no way at all, but there are plenty ways to accomplish something.

I'll way for Tom to reply so we can continue the discussion we were having.

  • 0

Back to SetProcessWorkingSetSize...

As far as losing users, I can understand where you're coming from, bangbang. I went through that dilemma myself. In some cases, it's appropriate to use the API and shut them up, and in some cases it's not.

For a non-trivial app, it's definitely not worth using. If you're creating (for example), a productivity app, the memory footprint isn't so important. A word processor, email client, InfoPath-type app or whatever... people really aren't going to care if it takes 50MB. On the other hand, for a trivial app (a sticky note program, a registry startup watcher, that sort of power-tool type of stuff), people WILL care, because they've got the idea stuck in their head that minor apps should be minor RAM users. That's not the right attitude, of course, but when you're making these kinds of apps, your userbase is quite a bit different. You get every johnny-knowitall from all over the Internet critiquing your app.

If you're charging for your app (regardless of what type it is), it's definitely not a good idea to use that API. Side effects like those **** people off. And ****ing off paying customers is an entirely different thing from ****ing off freebie hunters.

--

Danny Smurf

  • 0
  bangbang023 said:
I've told you a million times before, I get the basic code layed out then I worry about performce. It can't run well if it don't run at all. My code is definitely not the best, but neither is yours or anyone else's here, cause otherwise we'd be very rich, but my code is descent (lacking comments but not a problem for me.) Anything that works on my program works well and does not slow down the program. I wouldn't include a "feature" if it slowed down the proggy.

I think you have a correct approach. Optimization is always something you do last, and judiciously. As Kestrel has correctly stated, as have many others, cpu cycles(and memory) are cheaper than man-hours.

@dannysmurf

I agree 100%. End users suck. ;)

  • 0
  dannysmurf said:
Back to SetProcessWorkingSetSize...

As far as losing users, I can understand where you're coming from, bangbang. I went through that dilemma myself. In some cases, it's appropriate to use the API and shut them up, and in some cases it's not.

For a non-trivial app, it's definitely not worth using. If you're creating (for example), a productivity app, the memory footprint isn't so important. A word processor, email client, InfoPath-type app or whatever... people really aren't going to care if it takes 50MB. On the other hand, for a trivial app (a sticky note program, a registry startup watcher, that sort of power-tool type of stuff), people WILL care, because they've got the idea stuck in their head that minor apps should be minor RAM users. That's not the right attitude, of course, but when you're making these kinds of apps, your userbase is quite a bit different. You get every johnny-knowitall from all over the Internet critiquing your app.

If you're charging for your app (regardless of what type it is), it's definitely not a good idea to use that API. Side effects like those **** people off. And ****ing off paying customers is an entirely different thing from ****ing off freebie hunters.

--

Danny Smurf

I agree with you fully. My app has, in my mind, the nicest set of features for a note program (maybe lacking a few areas but it's only on 0.52). Either way, if people were going to pay for this and I knew they wouldn't nitch and moan, I would remove the call to that API in a flash, but, being a free program, I had nothing else to offer except the low ram usage selling point. I can't afford benefits or anythign like full 24/7 tech support lol.

  • 0

Well, what about an option based on my dialog proposal?

Make a dialog that shows up on first run that explains the memory management **** in easy words and then two radio buttons that allow you to choose to use the "memory preserving" option (SetProcessWorkingSetSize) or not.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • I maintain that the Cybertruck was a social experiment.  "Can we convince the massively insecure petrol guzzling, Dodge Ram loving, right wing idiots to buy a poorly built, underpowered, underspecified, electric vehicle that they know everyone will laugh at them in"
    • Wish you could set the WiFi country without setting an SSID. This would stop the warning on every boot.
    • Huawei's Mate XT successor launches this year with a performance and camera boost by Hamid Ganji Last year, Huawei reimagined our perception of folding smartphones by launching the world's first tri-folding device, Mate XT. Contrary to regular folding smartphones like the Samsung Galaxy Z Fold 6, the Huawei Mate XT utilizes a dual-hinge mechanism that allows the device to fold into a "Z" shape. The success of the Mate XT has allegedly prompted Huawei to release a sequel this year. Chinese tipster Digital Chat Station on Weibo says Huawei will release a successor in the second half of 2025. While the folding and screen solution remain unchanged, the tipster claims the second-generation Mate XT gets a faster processor and upgraded camera setup. Digital Chat Station says Huawei will also improve the device's accessories. Last year's Mate XT included an Aramid Fiber Case with an integrated rotating stand in the box as official accessories. Though the tipster doesn't mention quality improvements, Huawei could reinforce the phone's folding endurance. As for the release date, the first-generation Mate XT was released in September 2024, and the Mate XT 2 might also be released at the same time. Interestingly, Huawei announced its Mate XT, the world's first tri-folding device, on September 10 last year, just one day after Apple announced its iPhone 16 series. If Huawei wants to tease Apple again, we can expect the Mate XT 2 to drop simultaneously with the iPhone 17 series. While these devices are not in the same category, Huawei's rivalry with Apple is common knowledge. Tri-folding smartphones provide bigger screens at a more compact size compared to tablets. For example, the Huawei Mate XT has a screen size of 10.2 inches when it's fully open and 7.9 inches when folded once. Also, when you fold it twice, you get a 6.4-inch screen like regular smartphones. Huawei is now the biggest contender in the tri-folding segment, but Samsung may also join the race with a tri-fold version of its Galaxy Fold devices.
    • You can now measure internet speed and download videos using PowerToys Run by Taras Buria PowerToys Run is among my favorite modules, which I use daily (some of them should be integrated into Windows 11). This powerful utility is great for finding stuff, launching apps, navigating the web, and a lot more. Third-party modules help expand PowerToys Run's functionality and add additional capabilities like controlling Spotify, asking ChatGPT, and more. Now, there are three new modules you may find useful: speed test, video downloader, and vocabulary. The SpeedTest module uses Ookla Speedtest CLI for local execution without third-party tracking or ads. It has a modern, theme-aware user interface, and runs with a single command: just open Run and type spt to measure your internet connection speed. The result will show up in a new window with the ability to copy the result URL. The module also supports x64 and ARM systems. The VideoDownloader plugin lets you download videos from YouTube and other websites. You can specify the video quality and format (audio-only, for example) and select where to save the video. To make it work, open PowerToys Run, type dl and add a video URL. Finally, the Definition plugin from the same developer works as a powerful vocabulary that offers word definitions, word pronunciations, phonetics and synonyms, usage examples, and more. Note that these modules are not available in PowerToys out of the box. You need to download them from GitHub and install them manually. Here is how to do that: Download SpeedTest, VideoDownloader, or Definition plugins from their GitHub repositories. Extract downloaded plugins into %LOCALAPPDATA%\Microsoft\PowerToys\PowerToys Run\Plugins\ Open PowerToys Run (Alt + Space is the default shortcut) and launch plugins using their corresponding shortcuts (spt, dl, or def, all three can be customized in settings). You can also configure plugins in PowerToys Run settings. You can find more third-party modules for PowerToys Run on GitHub.
    • Showing people how to self host their own media is harmful, according to YouTube by David Uzondu YouTube has taken down a video from tech creator Jeff Geerling that demonstrated how to use LibreELEC, a lightweight operating system for turning devices into media centers, on a Raspberry Pi 5 for 4K video playback. The video, titled "I replaced my Apple TV—with a Raspberry Pi", originally published in May 2024, was removed in June 2025 under YouTube's "Harmful or dangerous content" policy. According to the violation notice, YouTube claimed the video showed "how to get unauthorized or free access to audio or audiovisual content, software, subscription services, or games that usually require payment." Image via Jeff Geerling Geerling strongly refuted YouTube's claims. He stated clearly, "I purposefully avoid demonstrating any of the tools that are popularly used to circumvent purchasing movie, TV, and other media content." He also emphasized that his own Network Attached Storage, or NAS, contains only legally acquired content. This isn't Geerling's first run-in with YouTube over self-hosted media tools. Last October, his tutorial titled "Better than Disney+: Jellyfin on my NAS" was hit with a similar strike for showing how to set up Jellyfin, an open source media server for organizing and streaming personal media. That strike was quickly overturned after an appeal. But this time, YouTube rejected his appeal, even though the LibreELEC video had been live for over a year, had racked up over half a million views, and contained no promotion of anything illegal. This whole thing feels a lot like what happened with youtube-dl. It's a simple command-line tool for downloading videos, used by tons of people for perfectly legal reasons like saving public domain content or backing up their own uploads. But that didn't stop the RIAA from hitting it with a DMCA takedown on GitHub, calling it a piracy tool. The community pushed back hard, and eventually it was brought back, thanks in part to support from groups like the Electronic Frontier Foundation who pointed out that not everything that can be misused is automatically bad. Side note, the youtube-dl project appears to be unmaintained (the last release was in 2021), if you're looking for an alternative, consider its very popular fork, yt-dlp. After the appeal was rejected, YouTube required Geerling to complete "policy training" to avoid a more serious, permanent strike on his channel. He eventually gave in and took the training. Anyways, if you're interested, he has uploaded the removed LibreELEC video to Internet Archive for anyone to watch.
  • Recent Achievements

    • Week One Done
      luxoxfurniture earned a badge
      Week One Done
    • First Post
      Uranus_enjoyer earned a badge
      First Post
    • Week One Done
      Uranus_enjoyer earned a badge
      Week One Done
    • Week One Done
      jfam earned a badge
      Week One Done
    • First Post
      survivor303 earned a badge
      First Post
  • Popular Contributors

    1. 1
      +primortal
      439
    2. 2
      +FloatingFatMan
      247
    3. 3
      snowy owl
      226
    4. 4
      ATLien_0
      212
    5. 5
      Xenon
      152
  • Tell a friend

    Love Neowin? Tell a friend!