Today my intstructor, where I'm intern, said I should use
HImage hi = null;
HOperatorSet.GenEmptyObject(out hi);
hi.Dispose();
hi = f.GrabImageAsync(-1.0);
Instead of
HImage hi = null;
hi = f.GrabImageAsync(-1.0);
Prototypes of used functions as follows
void HOperatorSet.GenEmptyObj(out HObject emptyObject);
HImage HFramegrabber.GrabImageAsync(double maxDelay);
I respect my instructor ,but I don't see any meaningful explanation at creating and disposing an object before calling hi = f.GrabImageAsync(-1.0); as that functions returns an instance of that object and therefore no need for Generating and Disposing object first, at least in my opinion.
So anyone can clarify if it is really needed or not. Thank you in advance.
I agree with you. Generally there is no use in creating and immediately disposing a variable.
As far as we can see from the code, HOperatorSet.GenEmptyObject doesn't interact with your f variable, so there would be no meaning in calling that method.
Also, there is no point in setting HImage hi to null, since that is probably the default already and it is set using the out parameter.
So my bet would be on:
HImage hi = f.GrabImageAsync(-1.0);
Most of the time Dispose() is called to release all managed resources that no longer in need. So let's assume that HOperatorSet.GenEmptyObject(out hi) method opens FileStream and saves reference to some field in new HImage instance. Later in code you would like to do other operation with this HImage instance and no longer need this FileStream or any other resources. It's a good moment to call hi.Dispose() that closes it before you proceed with doing anything else. But in any other case your instructor is misleading you.
There are a few classes in WinForms which have multiple purposes, some of which require resources and some of which don't. The one I'm most familiar with is Font. A Font instance encapsulates a combination of font settings as well as a GDI handle to a GDI font resource. The Font property setter of most WinForms controls will cause the controls to copy of the settings from the passed-in font object and store a copy of the passed in Font reference so that it may be returned by a call to the property getter, but will not cause the controls to actually use the passed-in font for drawing. Since the settings can be read from a Font object even after is is disposed, it is in fact possible to create and dispose Font objects when setting controls' Font properties; in some cases it may arguably be a reasonable least-of-evils approach:
If Font objects are created and abandoned without disposal, that will usually not cause too much of a GDI resource drain, but such wishful thinking doesn't represent good design.
A policy of calling Dispose on a control's old value of Font before setting a new value will require that every control own its own separate Font object, which will then encapsulate a resource the control will never use. The one advantage is that code which reads a control's Font property will be able to draw using that Font object directly.
Having controls hold references to font objects that are already disposed will make it possible for multiple controls to safely share the same font object, and will consume fewer GDI resources than either of the other approaches. The one limitation is that any code which reads a control's Font property and wants to draw with that font will have to use it to construct a new Font object for the purpose (and probably dispose of it after use).
IMHO, the fact that disposing Font objects immediately on creation is a useful pattern suggests that the Framework should have included separate types for the purposes of describing fonts (the purpose of a control's Font property) and encapsulating GDI font objects (the purpose of the Font parameter to string-drawing methods). If the latter type had included Dispose and the former type not, there would have been no question about how to use each. Since the Font type exists, however, along with code that uses it for those disjoint purposes, the eager-dispose pattern may be a reasonable least-of-evils approach.
I'm not sure that approach represents what's going on in your instructor's example since I'm not familiar with the types involved. It may be that the object returned by GenEmptyObject doesn't actually allocate any resources and its Dispose method does nothing (and stating that the particular object may be safely abandoned may be better than calling Dispose prematurely) but if the object acquires resources which won't be needed for its intended use, early disposal might possibly be appropriate if commented.
Related
I want to provide different parts of an application with independent Graphics instances which end up painting on the same base Graphics. Simply cloning the Graphics works, but since both instances refer to the same GDI handle, there are not independent. I can't use Begin and EndContainer as well since I have a method which has to provide the new Graphics instances. -so I cannot determine when to call EndContainer. The use case is quite similar to the Graphics.create() method in Java.
I've found some workarounds, but none of them works for a Graphics provided by the PrintController.
Is there any proxy-Graphics I can use? Or is there a possibility to create another Graphics for the same device for instance?
This sounds bad. Do not store references to a Graphics object, it only ever lives temporarily and is only valid while a Paint or PrintPage event handler is running. Do make sure to pass it as an argument to whatever method does the drawing instead of storing it in a field or a global variable.
If the method is altering the state of the object then use the Save() and Restore() methods to prevent this from causing problems in subsequent methods that use that same object. Cloning it is never necessary with this approach.
Graphics objects are not meant to be persisted. You could use a backbuffer approach by drawing to a Bitmap before your final render.
Perhaps you could raise an event to which listening drawing components could subscribe, and your calling code could chain these together. That way you could use the same Graphics instance without compromising GDI efficiency.
Not sure what exactly you're trying to do but you can use CreateGraphics() on a Control or Graphics.FromImage(xx) to create a new Graphics object for the control and/or image. There's also a few more functions in Graphics.FromXXX
A possibility would be to create multiple graphics objects which are pointing to multiple targets, for example an memory image. Then after done, combine all images into one.
But the thing I don't understand is, if all graphics instances should paint to the same target why do you need multiple graphics objects in the first place?
I was facing same problem, I found the only solution is to duplicate the drawings code line !!
Like the following:
e.Graphics.DrawString(points(i).pointText, myFont, Brushes.Blue, New Point(points(i).crossPointX4, points(i).crossPointY4)) : G.DrawString(points(i).pointText, myFont, Brushes.Blue, New Point(points(i).crossPointX4, points(i).crossPointY4))
I've been reading Rockford Lhotka's "Expert C# 2008 Business Objects", where there is such a thing as a data portal which nicely abstracts where the data comes from. When using the DataPortal.Update(this), which as you might guess persists 'this' to the database, an object is returned - the persisted 'this' with any changes the db made to it, eg. a timestamp.
Lhotka has written often and very casually, that you have to make sure to update all references to the old object to the new returned object. Makes sense, but is there an easy way to find all references to the old object and change them? Obviously the GC tracks references, is it possible to tap into that?
Cheers
There are profiling API's to do this but nothing for general consumption. One possible solution and one which I've used myself is to implement in a base class a tracking mechanism where each instance of the object adds a WeakReference to itself to a static collection.
I have this conditionally compiled for DEBUG builds but it probably wouldn't be a good idea to rely on this in a release build.
// simplified example
// do not use. performance would suck
abstract class MyCommonBaseClass {
static readonly List<WeakReference> instances = new List<WeakReference>();
protected MyCommonBaseClass() {
lock (instances) {
RemoveDeadOnes();
instances.Add(new WeakReference(this));
}
}
}
The GC doesn't actually track the references to the objects. Instead, it calculates which objects are reachable starting from global and stack objects at the runtime, and executing some variant of "flood fill" algorithm.
Specifically for your problem, why not just have a proxy holding reference to the "real" object? This way you need to update at only one place.
There isn't a simple way to do this directly, however, Son of Strike has this capability. It allows you to delve into all object references tracked by the CLR, and look at what objects are referencing any specific object, etc.
Here is a good tutorial for learning CLR debugging via SoS.
If you are passing object references around and those object references remain unchanged, then any changes made to the object in a persistence layer will be instantly visible to any other consumers of the object. However if your object is crossing a service boundary then the assemblies on each side of the object will be viewing different objects that are just carbon copies. Also if you have made clones of the object, or have created anonymous types that incorporate properties from the original object, then those will be tough to track down - and of course to the GC these are new objects that have no tie-in to the original object.
If you have some sort of key or ID in the object then this becomes easier. The key doesn't have to be a database ID, it can be a GUID that is new'ed up when the object is instantiated, and does not get changed for the entire lifecycle of the object (i.e. it is a property that has a getter but no setter) - as it is a property it will persist across service boundaries, so your object will still be identifiable. You can then use LINQ or even old-fashioned loops (icky!) to iterate through any collection that is likely to hold a copy of the updated object, and if one is found you can then merge the changes back in.
Having said this, i wouldn't think that you have too many copies floating around. IF you do then the places where these copies are should be very localized. Ensuring that your object implements INotifyPropertyChanged will also help propagate notifications of changes if you hold a list in one spot which is then bound to directly or indirectly in several other spots.
Imagine that I have a several Viewer component that are used for displaying text and they have few modes that user can switch (different font presets for viewing text/binary/hex).
What would be the best approach for managing shared objects - for example fonts, find dialog, etc? I figured that static class with lazily initialized objects would be OK, but this might be the wrong idea.
static class ViewerStatic
{
private static Font monospaceFont;
public static Font MonospaceFont
{
get
{
if (monospaceFont == null)
//TODO read font settings from configuration
monospaceFont = new Font(FontFamily.GenericMonospace, 9, FontStyle.Bold);
return monospaceFont;
}
}
private static Font sansFont;
public static Font SansFont
{
get
{
if (sansFont == null)
//TODO read font settings from configuration
sansFont = new Font(FontFamily.GenericSansSerif, 9, FontStyle.Bold);
return sansFont;
}
}
}
For items you wish to create once and then re-use there are two relevant patterns: Singleton and Cache. If you will re-use the item forever, the Singleton is OK. The memory allocated to that instance will never be cleared. If you will re-use the item for a while, but then maybe that function won't be used for a few days, I suggest using the cache. Then the memory can be cleared when the item is no longer in use.
If you are using the Singleton, you probably want to just init the Fonts directly rather than using the Lazy init pattern. To me, Fonts sound pretty simple and not likely to error out. However, if the item might fail during construction (perhaps due to a missing font file or something), then lazy pattern at least allows it to retry next time. You cannot redo a static initializer later, even if it fails, without restarting the whole application. Be careful to limit those retries!
Finally, the name of your class "ViewerStatic" raises a concern. There is an anti-pattern known as the "God" object. I call it the "bucket". If you create it, stuff will come. You will soon find all kinds of stuff being dumped in the bucket. Your ViewerStatic class will become huge. It would be better to have a class called "FontFlyWeights" and then another one called "ConstantStrings" or "SystemDialogFactory" ... etc.
That seems fine to me, but is it really necessary? The simple approach would be to just create new fonts and dialogs when you need them, then Dispose them if necessary and let the garbage collector clean them up.
Have you measured to see if the simple approach has a noticeable cost that makes it worth adding the complexity of caching shared objects?
Font being immutable distresses both the programmer and the GC, because you need to create a new instance every time.
Why is Font an immutable reference type then?
It simplifies the usage from the render system.
If the framework were to allow Font to be mutable, it would need to detect changes, and rework how it's rendering happens on a regular basis. Since Font creates a native resource, keeping this immutable prevents the system from worrying about having to recreate handles internally on a repeated basis.
Also, I disagree in terms of "Distress to the programmer". By making Font immutable, it makes it more obvious what is happening when the user creates a Font object. If you want a new Font, you need to create a new Font object, which in turn creates new native font resources. Making Font immutable makes it more clear what is happening - you're less likely to create a performance problem accidentally.
Were Font mutable, it would be less obvious that you were creating handles repeatedly as you changed your Font properties.
Well, ask yourself some questions.
First, is a font logically a mutable thing, like a grocery list, or an immutable thing, like a number? If you are modelling a grocery list in a program, it makes sense to make it mutable because you typically think of having one grocery list the contents of which change as you run out of or purchase particular items. But numbers you typically model as being immutable -- the number 12 is the number 12, now and forever.
I think of "Helvetica 12 point bold" as being a fixed, immutable thing, like a number, not something I can change.
Second, is a font logically more like a value that you can make copies of, or is it more like a single thing that you can refer to? I don't think of having "two copies" of Helvetica; I think of referring to Helvetica. Whereas numbers I think of as having different copies of for different purposes -- when I have 12 items on my grocery list and 12 keys on my keyring, I don't think of both of those things as "referring to 12".
Since I think of fonts as being immutable and referred to, rather than as mutable and copied by value, I personally would model fonts as immutable reference types. Perhaps your intuitions about fonts are different than mine.
They aren't structures because they need to have finalizers to wrap the underlying objects and provide a sensible IDisposable implementation. What happens if you Dispose() your own copy of a struct? Do you clone the handle each time?
It isn't really much stress on the GC...
It also allows the Font to be re-used safely without worry about it changing half way through an operation ;-p
I disagree this distresses the programmer. There are plenty of immutable types in the BCL which are used on a daily basis by programmers and don't cause any issues. System.String for example.
One of the benefits of being immutable is that you don't have to create a new instance every time. You can re-use the same Font type as often as you like because it's not going to change. On the other hand, if it were mutable, you would need to make a copy every time to help guarantee that no one else changed it out from under you.
Lastly, Font is not actually an immutable class in the strictest sense of the word. It implements IDisposable and in the Dispose method tears down the underlying native object.
You could argue that it distresses the developer. But you could also make the same argument in the opposite case.
For example:
// Let me just set the button to the same font as the textbox...
button.Font = textBox.Font;
// ...except that I want the button's font to be bold.
button.Font.Bold = true;
The above code would set a button and a textbox's font to bold at the same time if Font were mutable, contrary to the developer's expectations.
Font is a poorly designed object, which violates the Single Responsibility Principle, and the difficulties you cite stem from this. The problem with Font is that it encompasses two things: (1) a description of how a font should be drawn, and (2) a GDI font object for a font with those properties. The former type could be mutable without consequence, while making the latter type mutable would pose all sorts of problems.
Among other things, consider the question of how one should track the ownership of a typical control (e.g Button) Font property? If one will sometimes change the fonts associated with controls, should one create a separate Font object for each control, and Dispose of it when changing a control's font to something else, or should one keep a list of all the different fonts one is using so as to avoid creating an excessive number of identical Font objects, or what?
If there existed a FontDescription struct (which was mutable, and not IDisposable) and things like Control.Font were of type FontDescription (or better yet, Control exposed a SetFont method with parameter of type FontDescription), the above question could be answered pretty simply. As it is, the most efficient approach for setting the Font of a control is to create a new font object (if one doesn't already have a suitable one), immediately Dispose it, and then do the assignment. The "font description" part of the Font remains quasi-valid even after Disposal, and that's all that's really needed for the Control.Font property.
Please note this is done in WPF/C# and not in .net2.0 Winforms
I have a ListBox which contains objects of say Class X. Class X contains a BitmapSource object which is displayed in the listbox, so it displays similar to [Image] [Text]
This is loaded via the use of the CreateBitmapSourceFromHBitmap - note also that I call DeleteHBitmap to delete the handle of the HBitmap during this call, which is well known to do from posts I've seen on google/etc
I have a tree which contains said ListBox in each TreeViewItem - typically the tree has several items loaded. Users can drag/drop these images into different TreeViewItems. To handle these operation I manually call the operations:
<code>
ItemCollection.RemoveAt
</code>
<code>
ItemCollection.Insert
</code>
to move the images from the ListBox item collection, note when I insert I create a new Class X object to insert into the ListBox item collection
I have noticed I get a consistent memory leak from calling such operations several times, over the space of 5-10 mins of consistent dragging and dropping.
My question is:
Am I handling the moving of the BitmapSource's correctly? Is there something I'm doing to cause the Images to not be fully removed from the ItemCollection?
Or is there something fundamental I've missed?
Which is the definition of the variable that holds the image in you ClassX??? The problem may be in the fact that you are creating a new ClassX and the old one is no being deleted by the GC making the head have two different instance of ClassX.
Since you are using unmanged code (CreateBitmapSourceFromHBitmap) you should check if all the finalize method are correctly called (though close or dispose probably) and that the are no static references that can be pointing to your ClassX.
Remember that if you ClassX is not removed the Bitmap instance will be reachable in the graph made by the GC making it not to remove it from the heap.
I recommned using perfmon and add the .Net memory object to see if there are any object that survived finalize or pinned object, those are the one you are probably interested regarding the memory leak.
I hope it helps :P, but it will be nicer if you put the code of the ClassX.