Questions about Memory Usage in Windows Phone app - c#

How to reduce the memory usage in my C# Windows Phone apps?
Some instances:
1). To use the method: LockScreen.GetImageUri()
I can either add using Windows.Phone.System.UserProfile; in the top of the cs file.
or add the prefix Windows.Phone.System.UserProfile. in front of it, so that's Windows.Phone.System.UserProfile.LockScreen.GetImageUri()
Which one will use less memory?
2). Consider the scope of the variables, will it release memory more frequently if I break my method into multiple pieces, and run them one by one?
e.g. I need to render some images use WriteableBitmap, each might consume 1MB memory, if I have 10 or more images to render, it might exceed the memory limit soon.
Will it help if I render them in different methods?
3). Which is the better choice: Static or Non-Static?
It seems the static object will persist in the memory whenever the app is "alive" or "running", however, to use a non-static method we need to create an instance of it, which will consume the memory each time we do so (isn't it?).
ADD: If I create an instance of a class object, can I "Dispose" it anyway?
A special case: To use the IsolatedStorageSettings.ApplicationSettings;
I can either use it like:
IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;
if (!settings.Contains("IconSet"))
{
settings["IconSet"] = "Set1";
}
or I can also use
if (!IsolatedStorageSettings.ApplicationSettings.Contains("IconSet"))
{
IsolatedStorageSettings.ApplicationSettings["IconSet"] = "Set1";
}
Any difference? (regarding to the memory usage)
4). Deployment.Current.Dispatcher.BeginInvoke(() =>{})
Will this method release the memory it used at all?
Or do I need any special method to release the memory manually? Such as EndInvoke()?

No difference.
Objects like images that use large amounts of memory usually implement IDispose. To ensure that memory is released when it is no longer needed you should be calling dispose on objects when you no longer need the memory. Personally I find an easier way to manage this, is rather than explicitly calling Dispose on an object, wrap it in a using statement e.g.
using(Image myImage = new Image(Myfile))
{
// render myImage
}
People will say declare everything static as it is quicker. Personally I think when you try and declare everything static you're losing all the benefits of .NET as an OO language. Unless performance is absolutely critical, I discourage excessive use of static as in most instances the benefits are negligible and the compromises to your code structure are considerable.
EndInvoke() does not release memory
To answer Max Meng...
There is more than one Image class in the .NET framework. e.g.
http://msdn.microsoft.com/en-us/library/system.drawing.image(v=vs.110).aspx
WPF controls do not implement IDispose. Controls are owned by their parent controls. To dispose memory associated with the control call close on the page when you are done with it.
What is the correct way to dispose of a WPF window?
If IDispose is not implemented in a .NET Framework class that implies either there are no unmanaged or substantial resources associated with the class or alternatively that some other component is responsible for managing its resources.

Related

How do we distinguish between managed and unmanaged resources in C#? Is TextFieldParser unmanaged?

I recently learned how to use Microsoft.VisualBasic.FileIO.TextFieldParser to parse a text input. In the example given to me, the TextFieldParser is called using the keyword using
using (var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(new StringReader(str)))
Though after some further researches, I notice that the practice of using using keyword for TextFieldParser is not universal.
As far as I understand, .Net Framework has both managed and unmanaged resource. And when we use unmanaged resource, we should worry about memory leak and thus we should take care of the disposal of the unmanaged resource we use. One best way to do this is by putting them on using context.
All these drive me to have two questions in my mind, one particular and one general. Here are my questions:
The particular: Is TextFieldParser actually managed or unmanaged?
The general: Is there a definite way for us to know if a resource is managed or unmanaged(such as looking at X thing in the class, or such alike, or even check something from MSDN - if any should be checked - will do). I was told some guidance along my short programming experience such as that (i) most of the .Net classes are managed, (ii) System.Drawing classes have some unmanaged resources, (iii) beware of all database, network, and COM classes because they are typically unmanaged, etc... and the list goes on which I keep adding till now. But I wonder if there is any definite way to know this?
I would really appreciate if the more experienced could help to further guide me on this issue.
You're missing the point. Whenever any class implements IDisposable, you should call Dispose when you're done with it.
Whether the class uses unmanaged resources or not is internal to the class, you shouldn't care about it at all. Every class that uses unmanaged resources should also have a finalizer that clears up those unmanaged resources if you didn't dispose of the class explicitly. Dispose just allows you to clean its resources (both managed and unmanaged, though this doesn't necessarily mean freeing up the memory immediately) in a more deterministic and immediate fashion. For example, Disposeing a FileStream will release the file handle immediately, while if you don't Dispose (or Close), the file will be opened until the next collection and finalization.
EDIT:
To show that Dispose may also be necessary to clean up managed resources, we only have to look at event handlers. In particular, the case when you're subscribing on an event of a class that has a longer lifetime than you do:
var control = new MyHelperControl();
MyParentForm.Click += control.DoSomething();
Now, even if control goes out of scope, it will survive as long as MyParentForm - it's still referenced by the event handler. The same problem grows to absurd proportions when the parent has the same lifetime as the whole application - that's can be a huge memory leak. An example would be registering event handlers on the main form of an application, or on a static event.
There might also be other things that happen in the Dispose. For example, again with Windows forms, when you call Dispose on a Control, a whole lot of things happen:
All the unmanaged resources are released. Since Winforms controls are wrappers of the native controls to an extent, this is usually a lot of resources - the control itself, any pens, brushes, images... all of those are native resources. They will also be released if you forget a Dispose, since they all have finalizers, but it might take more time - which is especially painful when you create and destroy a lot of those objects. For example, there's a limited supply of GDI+ object handles, and if you run out, you get OutOfMemoryException and you're out.
Dispose of all sub-controls.
Remove any context menu handlers (remember, context menu is a separate component that's only linked to another control).
Remove any data bindings.
Remove itself from the parent container, if any.
If the control is a window with its own message loop, kill the message loop.
The funny part is that the unmanaged resources matter the least, really - they always have a finalizer. The managed resources are trickier, because you're more or less forbidden to handle managed references in a finalizer (because they might have already been released, or they might be in the middle of being released, or they might start being released in the middle of your finalizer... it's complicated). So doing MyParentForm.Click -= this.OnClick; is not a good thing to have in your finalizer - not to mention that it would require you to make every such class finalizable, which isn't exactly free, especially when you expect the finalizer to actually run (when you do a Dispose, the GC is alerted that this instance no longer needs a finalization).
The use of any classes implment IDisposable interface should be either wrapped in using (...) {} or be disposed nicely where appropriate.

Should variables be reused to optimize resource utilization?

I am Using Microsoft Visual C# 2010. I have several methods that use a large bitmap for local processing, and each method can be called several times.I can declare a global variable and reuse it:
Bitmap workPic, editPic;
...
void Method1() {
workPic = new Bitmap(editPic);
...
}
void Method2() {
workPic = new Bitmap(editPic.Width * 2, editPic.Height * 2);
...
}
or declare a local variable in each method:
Bitmap editPic;
...
void Method1() {
Bitmap workPic = new Bitmap(editPic);
...
}
void Method2() {
Bitmap workPic = new Bitmap(editPic.Width * 2, editPic.Height * 2);
...
}
The second way is better for code clarity (local variables for local use). Is there a difference in terms of resource utilization?
If you intend to keep the memory allocated to you can use workPic again after the method, you should register it as class variable. If not, you can free memory (always a good idea) by letting it go out of scope.
Allocating one variable doesn't matter much to the framework which manages memory. Only if you recreate a variable inside a tight loop you may benefit by reusing the variable. If you have basic types, you even reuse the same memory. Else, only the reference to the allocated memory is kept, so not that much benefit you have from there.
Note it is very important to Dispose your workPic since now you have a memory leak in the unmanaged memory behind Bitmap. Preferably use using.
Why Global Variables Should Be Avoided When Unnecessary
Non-locality -- Source code is easiest to understand when the scope of its individual elements are limited. Global variables can be
read or modified by any part of the program, making it difficult to
remember or reason about every possible use.
No Access Control or Constraint Checking -- A global variable can be get or set by any part of the program, and any rules regarding its
use can be easily broken or forgotten. (In other words, get/set
accessors are generally preferable over direct data access, and this
is even more so for global data.) By extension, the lack of access
control greatly hinders achieving security in situations where you may
wish to run untrusted code (such as working with 3rd party plugins).
Implicit coupling -- A program with many global variables often has tight couplings between some of those variables, and couplings
between variables and functions. Grouping coupled items into cohesive
units usually leads to better programs.
Concurrency issues -- if globals can be accessed by multiple threads of execution, synchronization is necessary (and too-often
neglected). When dynamically linking modules with globals, the
composed system might not be thread-safe even if the two independent
modules tested in dozens of different contexts were safe.
Namespace pollution -- Global names are available everywhere. You may unknowingly end up using a global when you think you are using a
local (by misspelling or forgetting to declare the local) or vice
versa. Also, if you ever have to link together modules that have the
same global variable names, if you are lucky, you will get linking
errors. If you are unlucky, the linker will simply treat all uses of
the same name as the same object.
Memory allocation issues -- Some
environments have memory allocation schemes that make allocation of
globals tricky. This is especially true in languages where
"constructors" have side-effects other than allocation (because, in
that case, you can express unsafe situations where two globals
mutually depend on one another). Also, when dynamically linking
modules, it can be unclear whether different libraries have their own
instances of globals or whether the globals are shared.
Testing and Confinement - source that utilizes globals is somewhat more difficult to test because one cannot readily set up a 'clean'
environment between runs. More generally, source that utilizes global
services of any sort (e.g. reading and writing files or databases)
that aren't explicitly provided to that source is difficult to test
for the same reason. For communicating systems, the ability to test
system invariants may require running more than one 'copy' of a system
simultaneously, which is greatly hindered by any use of shared
services - including global memory - that are not provided for sharing
as part of the test.
reference: http://c2.com/cgi/wiki?GlobalVariablesAreBad
The main thing to understand here is that field and variable is only holding a reference, the memory will be allocated to the object(s) created by "new".
So in both cases all created bitmap objects need to go through garbage collection.
Difference is that object only referenced in method will be ready to be collected right after method execution, when the object which still have reference in a field will be ready to be collected only when the object containing the field also will be ready to be collected.
The only case when it make sense to introduce the field is when you have the same object reused through the life cycle of the host object.
In cases when you recreate object in the beginning of the method definitely variable is recommended.

c# Static or Non Static Class

I have a c# windows forms mp3 player application. I have the audio files in my Resources folder and a separate "MyAudio" static class which handles all the audio related work like playing and increasing volume etc.
From my Form, I just call the play method using:
MyAudio.Play(track);
In the MyAudio class, I have a WindowsMediaPlayer object declared as:
private static WindowsMediaPlayer obj=new WindowsMediaPlayer();
My Question is, in terms of efficiency and less memory usage, is it better to declare MyAudio class as static or non static? Is it wise to create a Object of the MyAudio class in form and then call the methods or directly call using class Name?
Also is it good practice to declare the instance variables as static?
Your question is indeed broad, but there are few design principles that you can take care of, while you are designing a class:
Do I need the object and it's state throughout the application lifetime
Do I need to maintain the state of class variables for future use
Do I need to multi-thread or parallelize the application at any point of time
Do I need to decouple the component in the future and used in other scenarios like Ajax based web scenario
Important thing in this case is that you are keen to maintain the state for the application lifetime and the amount of memory usage is fine for the application environment, since after initializing you would be able to get all the data from memory and don't need to query a source like database. However, this is good for the scenario where you need to initialize once and read as a static information in the rest of the application. In case you plan to re query the information, then the part purpose of using static type would be lost
Let's assume in the future you need to parallelize your code for performance enhancement, then static will come to haunt you, since it would be shared among threads and invariably would need a synchronization construct like lock, mutex, which will serialize all threads and thus purpose would be lost. Same things would happen in a Web / Ajax scenario and your static component cannot handle the multiple parallel requests and will get corrupted until and unless synchronized. Here instance variable per thread is a boon, as they do task / data parallelization without requiring a lock, mutex
In my understanding static is a convenience, which many programmers misuse, by avoiding the instance variable and using at will, without understanding the implications. From the GC perspective, it cannot collect the static variable, so the working set of the application would invariably increase till it stabilize and will not decrease until and unless explicitly released by program, which is not good for any application, until and unless we are storing data to avoid network database calls.
Ideal design would suggest to always use the instance class, which gets created, does its work and gets released, not linger around. In case there's information that needs to be passed from one function to another like in your case from Play to Pause to Stop, then that data can be persisted to a static variable and modified in a thread safe manner, which is a much better approach
If we just take example given by you since it's a windows form, which does operations like Play, then static would be fine, as it is an executable running on a system, but for testing imagine a scenario that you initiate multiple instances by double clicking and play around on each one, by pressing different operations, then they all will access same static object and you may get a corruption issue, in fact to resolve such scenario you may even chose your class to be singleton, where at a given moment no more than one instance can exist in the memory, like it happens for Yahoo messenger, no matter how many times you click, always same instance comes up.
There are no static instance variables. However its best practice to define static members if they don't have anything to do with a particular instance of the class.

Garbage Collection in C#

So I'm making a client program for a MySQL database for a class and I have a few variables declared at the top of my form class that I use and reuse throughout the lifespan of the form. Every time the variables get used, I'm simply doing something like:
variableName = new VariableClass();
and then using it, primarily with DataSets/Tables. What I'm wondering is should I be explicitly freeing the memory before making another call to new or does C# take care of that for me?
There is no need to explicitly free .Net objects in C#. It runs on the CLR which is a garbage collected environment and hence the items will be cleaned up for you.
That being said ... it's unclear from your question if you are allocating these as fields or locals. If you are allocating them in fields and only using them in one function then you should move that declaration to a local. While the memory won't leak you will be holding onto the objects for significantly longer than is needed. This unnecessarily increases the memory footprint of your application.
It depends upon what the class of the variables does. If it uses resources that require disposal or if it uses unmanaged resources, you should implement IDisposable and ensure that they are disposed of correctly. If not, you can rely on the garbage collector to do its thing.

GarbageCollector, Dispose or static Methods?

I developed a few classes last month. They grow big (round 30-40 Methods each class).
I never take a thought of Memory Leaks, GarbageColletor or something like this (I must say this is my first own big project).
Now I have classes with Methods, 15 Classes Round About, each class min. 20 methods. 50% are Linq-Classes in the DAL, 50% BusinessClasses with BusinessLogic. NO Class uses global variables (no need), so theoretically I can make them static classes + methods. At the moment they aren't, I initialize a class object and use the class - and not disposing it.
Where I should start when I be angry of having Memory Leaks etc. when the system runs by ~100 users?
Don't worry about the methods of your classes since they do not consume memory: each method exists only once, in the class definition. What really takes memory is the data contained in the objects in the form of fields.
About disposing objects (I assume .NET here), it is not necessary unless you use unmanaged resources. The garbage collector will take care of freeing all the managed resources (that is, plain objects with their data) when necessary.
If you want more information about the .NET garbage collector and how to deal with memory leaks, you can for example look here: http://www.codeproject.com/KB/dotnet/Memory_Leak_Detection.aspx. But if you are at the start of your project, I would concentrate on getting a clear and maintainable design, rather than on memory management issues.
Whether you can make a class static does not depend on the use of 'global' variables but on the fact if a class uses instance fields (class member variables). If your methods do not use instance data the can be static (and there is a light preference to do so). If all methods are static you can make the class static as well.

Categories