Application Intermittently goes to Not responding - c#

We have an application built in .Net 4.5(C#, Winforms) which only in one production environment goes to NOt Respondingstate intermittently for 10 to 20 second.
I have written log on important lines. It hangs on loading heavy user controls and when data fetching calls are done.
The system on which it hangs has considerably low memory 2GB. I have almost reproduced the situation on a local machine by lowering the memory. My question is what are my options to avoid these hangs up.
The application memory does raises 200 to 300 mb.
The behavior is not consistant. Some time it takes 30 seconds to complete a task the next time it takes 3 seconds hardly.
The Not responding state comes usually in the start up.
My last attempt was i loaded the important assemblies on start up but i have no luck.
Lastly let me tell you that we have several third party controls.

If you are concern about memory allocation,
Use the .NET Memory Allocation option of the Performance Wizard found in the Analyze menu to create a Performance Session which will help you figure out what changes you need to make in your code to reduce memory usage.
We really need more info here. But a few suggestions:
Use the using keyword or call Dispose() on all disposable objects when
you are done with them
Make sure you unregister event handlers when you are done listening
for events
If you have lot of timers in your application,
This is only a problem with the System.Threading.Timer class if you don't otherwise store a reference to it somewhere. It has several constructor overloads, the ones that take the state object are important. The CLR pays attention to that state object. As long as it is referenced somewhere, the CLR keeps the timer in its timer queue and the timer object won't get garbage collected. Most programmers will not use that state object, the MSDN article certainly doesn't explain its role.
System.Timers.Timer is a wrapper for the System.Threading.Timer class, making it easier to use. In particular, it will use that state object and keep a reference to it as long as the timer is enabled.

Related

Navigation of pages and running in the background

In UWP (XAML / C#) I use Frame.Navigate(typeof(Page2));, and in C# of Page2 I use timer and when I use Frame.GoBack();, the frame really goes back, but the timer is not stopped - I mean the page and all its components are still running in the background, and the app is consuming too much RAM because of that. How can I "kill" the page?
note: if user uses this navigation 10 times, the page is 10 times in the background and it is bad..
It is important to understand that CLR garbage collector is the one who is responsible for "killing" unused objects. An object (and all of it's members) becomes "unused" when it is no longer referenced.
When you start a Windows.UI.Xaml.DispatcherTimer, it adds itself to a timer collection inside the current Dispatcher, thus, creating a direct reference between the Dispatcher and the timer. The timer, in its turn, holds a reference to the page where it is running. Since the Dispatcher is a global object, it will keep your page alive until the timer is stopped.
There can be other causes of memory leak (it is a pretty broad topic), including:
Other sources of direct or indirect references to your page;
Subscriptions to static events;
Complex data bindings like {Binding Path=Property.Subproperty};
I would suggest you to use a memory profiler to find memory leaks if the above doesn't help, such as the Diagnostic Tools included in Visual Studio 2015.

Memory Management Ideas?

I'm writing a game in C# with SharpDX...
So, for drawing a frame, currently i'm using a Timer, with interval set to 1;
But this is too slow for a game, so i want something faster...
First of all, if I use another thread for the game (and another for the Window itself) and i use a "[while (InGame)]" statement, it is fast, but the GC will never release a single object, and the memory usage just going up and up...
IF I use the SharpDX built in "RenderLoop" function, it is fast also, but the GC still doesn't do anything...
I've tried to override the Window form "WndProc" function, but the game only refresh itself then i'm moving the mouse like a crazy men...
This is my first real game, with a lot of functions,
so if any of you have any idea, how would i fix it, or what should I use, I would appreciate it...
There must be something in the Window Form lifecycle like a
void FormLife
{
WndProc();
HandleEvents();
etc...
}
(It was just a hard example...)
OR how can i force the GC to do its job, at the end of the while(InGame) state ?
I've tried GC.Collect(); but its dont work...
Don't put your game logic in the UI classes.
Use a multimedia timer and a dispatcher to return to main thread for rendering. From my experience a cycle of 5mSec works well. (Lower will waste CPU time).
Use dispatcher priority of Input so that the timer won't choke the UI and prevent it handling user events.
On timer event, if the previous update hasn't completed, return immediately without doing anything (you can use System.Threading.Interlocked.CompareAndExchange as a cheap sync method).
To make game run faster, try to reuse objects and change their states or to pass short living immutables so that the GC won't delay your program.
Use the IDisposable pattern where applicable.
If GC.Collect does not free memory you have a memory leak. Use the memory profiling tool of your choice to spot the leak (PerfView, Windbg, .NET Memory Profiler, YourKit, ....)
Besides this the best allocation is no allocation at all. If you reuse objects and keep unused objects in a pool you can get rid of GCs almost entirely. Even if you stay away from Gen 2 collections which can block your game for hundreds of ms you also need to keep a sharp eye on Gen 0/1 collections which can also cause noticeable delays.
See http://social.msdn.microsoft.com/Forums/vstudio/en-US/74631e98-fd8b-4098-8306-8d1031e912a4/gc-still-pauses-whole-app-under-sustainedlowlatency-latencymode-despite-it-consumes-025gb-and?forum=clr
You don't typically have to worry about memory management. If you are making sure not to hold on to references then the garbage collector should do its thing automatically based on memory pressure.
You can force it yourself using GC.Collect but you need to be absolutely certain you really need to. Most of the time its not required. Check this thread for more info and points to consider: Best Practice for Forcing Garbage Collection in C#
Since the objects are not being collected you must be holding a reference to them somewhere.
You didn't post much code so it is hard to say where you are holding a reference.
In the past I've used windbg to find the root cause of of memory issues. VS2013 has a memory profiler built in (might be easier to use).
A common case I've seen of holding references is via event subscription. If you have subscribed to any events you have to make sure you unsubscribe to release the object. see Why and How to avoid Event Handler memory leaks? for more details. That doesn't look like your problem.

C# Production Server, Do I collect the garbage?

I know there's tons of threads about this. And I read a few of them.
I'm wondering if in my case it is correct to GC.Collect();
I have a server for a MMORPG, in production it is online day and night. And the server is restarted every other day to implement changes to the production codebase. Every twenty minutes the server pauses all other threads, and serializes the current game state. This usually takes 0.5 to 4 seconds
Would it be a good idea to GC.Collect(); after serialization?
The server is, obviously, constantly creating and destroying game items.
Would I have a notorious gain in performance or memory optimization / usage?
Should I not manually collect?
I've read about how collecting can be bad if used in the wrong moments or too frequently, but I'm thinking these saves are both a good moment to collect, and not that frequent.
The server is in framework 4.0
Update in answer to a comment:
We are randomly experiencing server freezes, sometimes, unexpectedly, the server memory usage will raise increasingly until it reaches a point when the server takes way too long to handle any network operation. Thus, I'm considering a lot of different approaches to solve the issue, this is one of them.
The garbage collector knows best when to run, and you shouldn't force it.
It will not improve performance or memory optimization. CLR can tell GC to collect object which are no longer used if there is a need to do that.
Answer to an updated part:
Forcing the collection is not a good solution to the problem. You should rather have a look a bit deeper into your code to find out what is wrong. If memory usage grows unexpectedly you might have an issue with unmanaged resources which are not properly handled or even a "leaky code" within managed code.
One more thing. I would be surprise if calling GC.Collect fixed the problem.
Every twenty minutes the server pauses
all other threads, and serializes the
current game state. This usually takes
0.5 to 4 seconds
If all your threads are suspended already anyway you might as well call the garbage collection, since it should be fairly fast at this point. I suspect doing this will only mask your real problem though, not actually solve it.
We are randomly experiencing server
freezes, sometimes, unexpectedly, the
server memory usage will raise
increasingly until it reaches a point
when the server takes way too long to
handle any network operation. Thus,
I'm considering a lot of different
approaches to solve the issue, this is
one of them.
This sounds more like you actually are still referencing all these objects that use the memory - if you weren't the GC would run due to the memory pressure and try to release those objects. You might be looking at an actual bug in your production code (i.e. objects that are still subscribed to events or otherwise are being referenced when they shouldn't be) rather than something you can fix by manually taking out the garbage.
If possible in this scenario you should run a performance analysis to see where your bottlenecks are and what part of your code is causing the brunt of the memory allocations.
Could the memory increase be an "attack" by a player with a fake/modified game-client? Is a lot of memory allocated by the server when it accepts a new client connection? Does the server handle bogus incoming data well?

Periodical WMI Query Causes Memory Leak?

I am fairly new to the .NET programming and I am currently developing a computer health monitoring system which is in its infant stage now. I will be using C# 2010 and querying computer information by using WMI queries.
Before I could further develop the application, I have created a mini test app to test out my classes and its methods. The flow of the test app is as follow:
App startup
Input hostname, username and password
Query button clicked and the querying methods fired.
A textfield on my UI gets updated, printing out the result of the queries.
I have a class called Machine, which contains properties such as the CPU Name, and some update-able properties like the current CPU usage. In that class, I have 2 main methods, GetStaticSysInfo and GetDynamicSysInfo, where the first method queries the system info that does not change over time, and the later one queries information like CPU and memory usage. I have another method named Refresh that I use to wrap around the GetDynamicSysInfo method.
As I am using WPF for my UI, I have used the DispatcherTimer to periodically queries the machine, and prints the updated info to the textfield on the UI after the Query button has been clicked. However, I noticed that each of the time I called machine.Refresh(), the memory usage of the app increases by a bit (few hundred KBs). I can't really figure out what's wrong with the program and I would appreciate that someone could provide some advices on this.
Please let me know if you need more information, or any portions of the code.
Thanks in advance.
EDIT: I have added a GC.Collect() on the Timer_Tick method, and it seems like the memory usage still climbs but it is lowered once every few timer ticks. It is still increasing, but at a slower rate. Is this the correct way of doing it and will it impair performance in the long run?
Except for diagnosis purposes you should never call GC.Collect(). The runtime has much better algorithms for when the GC should run. Also, calling Collect() too often can result in objects being promoted to 1st or 2nd generation, which actually means they are collected more slowly after they are not used anymore, i.e. increasing your memory footprint.
If the memory goes down again (to the previous value) after manually collecting, then you have no memory leak. Since the GC doesn't run all the time, you will have increased memory in between GC runs. That is no cause for concern.

Causes for web service memory leak

We have a web service that uses up more and more private bytes until that application stops responding. The managed heap (mostly Gen2) will show some 200-250 MB, while private bytes shows over 1GB. What are possible causes of a memory leak outside of the managed heap?
I've already checked for the following:
Prolific dynamic assemblies (Xml serialization, regex, etc.)
Session state (turned off)
System.Policy.Evidence memory leak (SP1 installed)
Threading deadlock (no use of Join, only lock)
Use of SQLOLEDB (using SqlClient)
What other sources can I check for?
Make sure your app is complied in release mode. If you compile under debug mode, and deploy that, simply instantiating a class that has an event defined (event doesn't even need to be raised), will cause a small piece of memory to leak. Instantiating enough of these objects over a long enough period of time will cause all the memory to be used. I've seen web apps that would use up all the memory within a matter of hours, simply because a debug build was used. Compiling as a release build immediately and permanently fixed the problem.
I would recommend you view snapshots of the stack at various times, and see what's using up the memory. If your application is using Java, then jmap works extremely well - you just give it the PID of the java process.
If using something else, try Lambda Probe (http://www.lambdaprobe.org/d/index.htm). It doesn't show as much detail, but will at least show you memory use.
I had a bad memory leak in my JDBC code that ended up being traced to a change in the JDBC specification a few years ago that I missed (with respect to closing statements and such). It took a combination of Lamdba Probe and then jmap to localize the problem enough to fix it.
Cheers,
-R
Also look for:
COM Assemblies being loaded
DB Connections not being closed
Cache & State (Session, Application)
Try forcing the Garbage Collector (GC) to run (write a page that does it when it loads) or try the instrumentation, but that's a bit hit and miss in my experience. Another thing would be to keep it running and see if it runs out of memory.
What could be happening is that there is plenty of memory and Windows does not signal your app to clean up. This causes the app to look like its using more and more memory because it can, when in fact the system can reclaim the memory when it needs. SQL Server and Exchange do this a lot. The idea is why cause a unnecessary cleanup when there are plenty of resources.
Rob
Garbage collection does not run until a request for memory is denied due to lack of available memory. This can often make things look like a memory leak when one is not around.
Do you have any events and event handlers within the service? Services often have static variables, and if you are creating event handlers from the static instances, connected to a non-static instance object, the static will hold a reference to the instance forever, which will stop it from releasing.
Double check that trace is not enabled. I've seen instances of trace slowly consuming memory until the app reaches it's app pool limit.
For what it is worth, my issue was not with the service, but the with HttpClient that was calling it.
The client was not properly disposed, so it kept the connection open and the memory locked.
After disposing the client the service released the memory as expected.

Categories

Resources