Memory problem with application in C# Windows Forms - c#

I have an application in C# which reserves too much memory when it wasn't supposed to. The executable is ~100Kb and the whole application is a couple thousands lines of code.
It's main component, has a timer which is responsible of creating events (instances of a class with a couple of attributes) and sending them to this http://timeline.codeplex.com/. The way the timeline accepts events, is by calling a ResetEvents function and passing a list of events. Because I have a timer, I put that inside the timer's code.
Running it like this, the application goes up to 300Mb of memory and I just end it to avoid crashing. If I remove the call of ResetEvents from the timer, then the application runs more smoothly consuming 60-70Mb. The application without the timeline, should run at 10-20Mb. There are no graphics or anything that could possibly use more than that. My guess is that something might be wrong with the timeline.
EDIT:
Here's a part of the code:
List<TimelineEvent> events = new List<TimelineEvent>();
...
inside timer
TimelineLibrary.TimelineEvent newevent = new TimelineLibrary.TimelineEvent();
...
newevent.StartDate = starttime;
newevent.EndDate = endtime;
newevent.Id = id;
newevent.Title = title;
newevent.Description = description;
newevent.Link = url;
newevent.EventColor = color;
events.Add(newevent);
timeline.ResetEvents(events);
...
This code is inside the timer. I just create a TimelineEvent, add it to a list and call ResetEvents. Removing that last line, doesn't cause the memory problem.

Since it is very hard to see what your problem is without more code, I suggest trying some kind of memory profiler to locate where and when the memory gets allocated.
Try for example RedGates Memory Profiler, they have a time-based trial.
Follow this walk-through to get up to speed and learn a bit what to look for and how.
For more options regarding .NET memory profilers, see this thread.
Good luck!

What is the type of the events variable you passed to ResetEvents?
Without seeing the code, the only suspicious behavior I can in what you did post, is that perhaps the ResetEvents method does not really clear the collection it receives, but instead does something on the state of the timeline variable.
Using a memory profiler is a great idea. If you expect people here to help you find a memory leak otherwise, please post more of your code. Ideally, you could reproduce the problem with minimal code and then post that.

Related

seeking possible memory leak with C#/C++ wrapper

I have a C# program that calls a C++ DLL. The wrapper code for the function is question is shown below.
As this function is called repeatedly, memory use continues to grow and it appears as if there's a memory leak. And it appears that the issue is associated with the matchingFragments->Add line in the code below. If I comment out that line, memory use is stable.
In previous iterations of this program, where matchingFragments wasn't a list but was set to a fixed number of elements, memory use would be stable throughout repeated calls to this function. So I suspect some memory isn't being freed somewhere, but I don't know what the issue is, whether it's matchedFragments, returnedFragments, or neither. Nor do I know any of this well enough (I'm a C developer struggling with this) to know how to debug this, so any suggestions would be appreciated.
bool SearchWrapper::SpectrumSearch([Out] List<FragmentWrapper^>^% returnedFragments)
{
vector<Fragment> matchedFragments;
// perform the search
bool isSuccess = _pSearchMgr->PeptideSearch(matchedFragments);
// Convert data back to the managed world
returnedFragments = gcnew List<FragmentWrapper^>();
for (auto frag : matchedFragments)
{
returnedFragments->Add(gcnew FragmentWrapper(frag));
}
return isSuccess;
}
Turns out the actual fix to my issue was the need for a finalizer for the FragmentWrapper class. There was a destructor but not a finalizer. Once I added the finalizer, the memory leak went away.

Undocumented .NET code related to Multi-Touch Manipulations throwing exception

A favorable outcome would be preventing this exception, preferably, or at least handling it gracefully.
I am getting an exception thrown within Microsoft code. On top of that, the method throwing the exception is System.Windows.Input.Manipulations.ManipulationSequence.ProcessManipulators, which I can't find in Microsoft Reference Source.
When the exception is thrown, I can see that one line down in the Call Stack window it references Windows.Input.Manipulations.ManipulationProcessor2D.ProcessManipulators, which does exist in Microsoft Reference Source.
But as you can see, it doesn't have a sibling class named ManipulationSequence.
As for the exception itself, it is a System.Argument.OutOfRangeException with a value of Timestamp values must not decrease. Parameter name: timestamp Actual value was 6590630705479.
The fully qualified signature of the method throwing the exception is System.Windows.Input.Manipulations.ManipulationSequence.ProcessManipulators(long timestamp, System.Collections.Generic.IEnumerable<System.Windows.Input.Manipulations.Manipulator2D> manipulators, System.Windows.Input.Manipulations.ManipulationSequence.ISettings settings)
It appears as if one other person in the universe has had this problem, but it could not be reproduced according to the only comment.
I have 6 MediaElement objects on a canvas that are all running videos when being manipulated, so I feel as though it might have something to do with the CPU being taxed and slowing down, possibly making timestamps be sent into the method out of order (though the same problem occurs when using Image rather than MediaElement). The exception happens sporadically, sometimes it will happen after just a few seconds of messing around with the objects, sometimes it can go for a few minutes or more of manipulating the objects.
My code that does the actual manipulation within ManipulationDelta looks like this:
//Get current values to manipulate
TransformGroup group = (TransformGroup)element.RenderTransform.Clone();
TranslateTransform translate = (TranslateTransform)group.Children[0].Clone();
ScaleTransform scale = (ScaleTransform)group.Children[1].Clone();
RotateTransform rotate = (RotateTransform)group.Children[2].Clone();
//...does manipulations on each by changing values...
//Apply transformation changes
group.Children[0] = translate;
group.Children[1] = scale;
group.Children[2] = rotate;
element.RenderTransform = group;
I have a Storyboard in XAML messing with the RotateTransform, so I can't really use MatrixTransform.
I am creating this using WPF with .NET 4.5.1. The error occurs in both Windows 8.1 and Windows 7. Any ideas on how to prevent this exception from occurring?
Some thoughts as I investigate the problem:
I also have ManipulationInertiaStarting in play here as a possible
cause of this error.
I just added e.Handled = true; to the end of ManipulationCompleted, which wasn't there before. I haven't got the error since (though, again, very sporadic, so it is hard to tell when it is fixed).
If a ManipulationDelta method is not yet complete, and it is hit again from user input, could there be some sort of race condition occurring where the first method hit is starved for CPU resources and the second runs through, then when the first method finally completes the timestamp created is in the past?
Per a comment, this isn't likely.
I conferred with a co-worker to gain better understanding. He helped me realize I can't swallow the exception from within my methods that handle manipulation events because the exception is happening before it gets there, in the actual creation of the manipulation data. So the only place I can handle the exception is on App.Main() (the first place in the Call Stack where my code exists), which makes handling it gracefully all the more difficult.
I had this exact problem myself.
After a lot of testing it could be reproduced with slower machines under heavy load.
The Application was for Digital Signage and showed a lot of different items ( Video, Html , Images , etc ) and had also some animations.
I am not sure about it but it seems to be a problem of handling the input events in time.
For myself i could "solve" this issue with outsourcing code from the manipulating to other code asynchronous and also profiling and rewriting code performance-wise.( shortened the path to run inside the event as much as possible and did everything needed to do also later with a Task )
Also i added an Exceptionhandler to my application to "ignore and log" this issue, because it had no other impact.
Feel free to contact me for more info on this.
PS: this is my first answer here, so i hope it is alright the way i wrote it
I had similar problems when developing for WinRT.
It's sometimes possible to use DispatcherUnhandledException event to ignore one particular exception. To do that, add event listener, check if exception is the one you want (because it's generally bad idea to suppress all exception), and then set Handled property.

Accessing value from WinRT component that is continously updated from managed code

I am writing an application that will do some processing on the live preview images on windows phone 8. To achieve a good performance, I decided to use to the native interfaces provided with new sdk. Everythings work Ok for initializing the camera in native side, and feeding frames to a Image component in xaml. Now, I will write the code that will run in OnFrameAvailable method.
My problem is getting a processed value from the native component. Just to make things as simple as possible I just set an integer value in OnFrameAvailable and wrote an accessor of this value through a WinRT component to make it accesible in managed side.
I got stuck on what is an elegant way of accessing this value. When I try to access it in a loop in a thread i get the notorious "attempted to read or write protected memory " exception. I know the code does not make very much sense but I tried to minimize to point out the issue.
Here is how I do it:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
nativeCapture = new NativeCapture();
while (nativeCapture.Done == false) ;
viewFinderBrush.SetSource(nativeCapture.NPhotoCaptureDevice);
DrawElementThread = new Thread(drawElementsFunction);
DrawElementThread.Start();
base.OnNavigatedTo(e);
}
void drawElementsFunction()
{
while(true)
{
int a = nativeCapture.DetectedRectangleCoordinates; // Exception occurs here
}
}
Here you'll also notice that I am accsessing another value, Done, but I dont get the exception for it. However, I should note that is just set in the constructor of the native component whereas DetectedRectangleCoordinates is set everytime OnFrameAvailable called which I expect anytime a preview frame from the camera is available.
Therefore, I susptected that there might be some locking mechanism on WinRT components. Each time the OnFrameAvaible method called DetectedRectangleCoordinates becomes unaccessible. However, I could not find a statement about this and couldn't figure out how to debug such a thing.
I would really appreciate if you provide me with some pointers related to this or similar issues? Is it something related to access mechanisms in WinRT components? Or it is a bad threading practice I am doing? If so, how would I synchronize the thread in managed code and native code?
EDIT:
Putting a breakpoint on the line giving the exception and stepping does not cause the exception, and I get the expected value.
EDIT:
I put a breakpoint on the get function on native side. this pointer is pointing to null there. I could not understand why it is because it is being called from the object that is just constructed. ( nativeCapture object).
I have worked quite some time on what may be going wrong, but adding the code to Loaded event handler of the page solved the issue. I am not sure what it is related about, but when the code piece I have given in the question is run in OnNavigatedTo method, nativeCapture component might have self null pointer (this->) on its methods.
I hope this could help people if they have similar problems.

Can I Trust LoadOperation.Completed event

Suppose that we have the code shown below,
LoadOperation lop=_dsrvX.Load(_dsrvX.GetUserDetails(userID));
lop.Completed +=(s,a)=>
{
Debug.WriteLine("Completed but,
First I load it then I registered Completed evet!");
}
I see this type code everywhere so I wonder is it right?
As I know when you call domainService methods this automatically fills domain service object's related EntitySet.
Suppose that LoadOperation(Can be Submit,Invoke ops.) completed rapidly and when I passed to the next line where I register completed event everything has done.Is it possible? It seems hard to achive that but can you give me 100% guarantee?
If you can't guarantee that I'm asking if there is a method of calling OperationBase objects manually?
Any comment will be appreciated.
Well, this is a crazy world, I would not give 100% guarantee of anything :P - But I do not think it should be a problem. If this bothers you, you can pass the callback as a parameter, like this:
_dsrvX.Load(_dsrvX.GetUserDetails(userID), userDetailsCallBack, null);
(...)
void userDetailsCallBack(LoadOperation<UserDetails> op)
{
//do anything with the results
}
or, to simplify even further:
_dsrvX.Load(_dsrvX.GetUserDetails(userID), (op)=>
{
//do anything with the results
}, null);
Yes you can trust it - 100% guaranteed!
If you dig into the code behind the asynchronous Load method, you will see that it starts up another thread, to do the actual load, then returns immediately.
That separate thread then prepares for a service call, performs the service call, and eventually returns the resulting data.
It cannot trigger the Completed event until that is all done and we are talking "a lot" of code to get through, not to mention waiting on a web-service, whereas the return is pretty much instantaneous after the thread was started. i.e. no chance for the other thread to complete and interrupt it.
There is 0% chance that the load will complete before you add the handler on the next line.
The usual approach is to provide a callback or anonymous method instead, but your existing code is fine. MS knew what they were doing when the designed it that way :)
I had this argument with Jon Skeet, on a related question, and his reaction was that you don't know what the Load method is doing so it "might" happen faster than the return... My pragmatic answer was that we know exactly what is going on, by design, and it 100% returns before the Load even commences

GC.Collect in a loop?

I found this piece of code inside System.Web.ISAPIRuntime using Reflector
public void DoGCCollect()
{
for (int i = 10; i > 0; i--)
{
GC.Collect();
}
}
Can anyone comment on this? Is there a reason to do GC.Collect() in a loop? Why 10 times and not 3, 5 or 20? Analysis indicated that it's not used inside .net framework but it's public so I suppose that IIS could call it...
edit :
Just for clarification purposes : I have never called GC.Collect and I have no intentions of using it. I know it's a bad idea in most (if not all) cases. The question is why .net framework does it. Thanks for all your answers.
Yes, that's horrible. Firstly, you shouldn't need to do it at all. However, if you really want to force garbage collection as hard as you can, and wait for it to finish, you should probably use:
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
GC.WaitForPendingFinalizers();
// Collect anything that's just been finalized
GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced);
Really not a nice idea though.
Looks truly horrible :)
I don't think you're going to get a better explanation that "one of Microsoft's programmers is pretty clueless, and apparently, no one else bothered to look at his code before it was checked in". ;)
It does look scary though.
It's a fairly common response to bugs you don't understand though. For whatever reason, you're trying to call the GC, and somehow, calling it doesn't seem to solve your problem (perhaps the real problem was just that you should wait for the finalizer thread or something), so the naive solution is obviously "Well, I'll just keep calling it then".
Similar to pressing 'print' repeatedly until your document is printed.
Perhaps you should submit it to thedailywtf.com though.
Shouldn't things like this be pointed out to Microsoft? Would it do any good to post this on the Connect site?
I really like the Mono implementation of this method:
public void DoGCCollect ()
{
// Do nothing.
}
Probably the developer intended to write something similar and this is just a typo.
Looks like someone with a doomsday complex wrote it with connotations that they'd be ending the world with a 10 second timer...
This is not a good idea because you really ought to trust the garbage collector to do its job without being invoked specifically from your code.
99.9% of the time you never need to call the GC from your code.
First of all it is not a good idea to call GC.Collect(). Calling it multiple times has little effect.
However, you sometimes see the pattern of calling Collect(), then WaitForPendingFinalizers(), and then finally Collect() again. The idea behind this is to ensure that instances with finalizers are also reclaimed, as they will survive the first collection. Keep in mind tough that this will induce a delay in the application and it should very rarely be needed.

Categories