Sunday, May 1, 2011

How does GC and IDispose work in C#?

I remember i was loading in images by streaming it from the net straight into a bitmap. close the stream, return the bitmap and held it in an image control.

I excepted when i did = loadPicture() the first bitmap would be freed like a smart pointer would do in C++. But it didnt and i consumed a lot of ram until i called dispose. So my question is.

How does the GC and Dispose able objects work in C#? and why isnt it implemented like a smart_ptr?

From stackoverflow
  • The GC kicks in when the runtime feels it is necessary.

    The basic rule is: when you use an Disposable type (IDispose), then you (as the programmer) should release the resources used by that type as soon as possible, by calling Dispose when you do not longer need to use that type. For instance, when you read a file, you close that file as soon as you've done reading it. (Calling close will also call dispose in this case).

  • References are not smart pointers. Letting a reference-variable go out of scope, replacing it with another value, and/or setting it with null all do exactly nothing.

    This is simply part of the CLI /GC design...

    Gargage Collection (GC) will run when needed, and should clean up the managed memory used, and (if a finalizer is provided) any unmanaged resources too. But for deterministic cleanup: that is the entire purpose of IDisposable. It is your job to Dispose() such objects when you have finished with them - either via using, or by handing it to something else which assumes this responsibility (common, for example, with streams/readers etc).

    using (StreamReader reader = new StreamReader(myfile)))
    {
       ...
    }
    
    Dead account : +1. Im sure this question has been asked already :)
    acidzombie24 : Are you saying i don't 'need' to dispose of anything?
    Anton Tykhyy : Only in the sense that even if you don't, resources will eventually be freed (if they implement IDisposable correctly, that is). In practice, this is merely a safety net. You want to release unmanaged resources as soon as possible.
    Lucero : "...all do exactly nothing" is not the full truth. By setting references to null, you might allow the memory to be released earlier because the reference is no longer seen as "live" reference in the system when the GC runs.
    Mudu : As far as I know, finalizers are not guaranteed to be called. Usually they are, but there's no garanty. See http://tinyurl.com/cr4uo2 (MSDN: Object.Finalize Method) under "Remarks" for details.
    Marc Gravell : @Lucero - I mean as an *active* operation; the runtime is indeed to do more clever things. @Mudu - indeed.
    Marc Gravell : @acidzombe24 - choosing not to Dispose() things would be risky - you can run out of unmanaged resources without really using much managed memory, so GC wouldn't kick in. Early versions of VS suffered from this, IIRC. You should always try to release (Dispose()) such objects ASAP once you are finished with them.
    configurator : @Lucero: If the variable is not referenced after the point where you set it to null, it's a no-op, because once you have reached the point where a variable is not referenced any more, the JIT knows and it is the same as leaving scope. Setting it to null is also JIT-optimized away.
  • smart_ptr are reference counted. While this allows for deterministic release of their resources when they are no longer referenced by any code, they do have their problems of their own: assigning references always requires the counter to be updated, circular references fail to be released automatically causing memory leaks, the memory manager is invoked more often.

    The GC in .NET is a sweeping collector. It starts at any time when it feels that memory should be released (usually triggered by some memory usage condition, but not deterministic) and starts by building a list of all live references in the system (including the ones in CPU registers, nested references etc.). This works since we are in a managed environment where you cannot do pointer arithmetic etc. - the system can track all references. After the list of live references has been built, it basically releases all memory not known to be used anymore. Of course, this is just the basic sketch, for efficiency and management of unmanaged resources there is more to it like object generations, finalizers, etc., but that is not important for the basic understanding of how it works.

    The IDisposable interface is used to implement the disposable pattern, which helps when you are working with objects that should be disposed in a deterministic way. The pattern is so that Dispose() is called explicitly when the object is no longer needed, therefore releasing unmanaged resources or closing handles etc., but not releasing its memory. This will be done by the GC later on, but it does not matter that this happens later, because the deterministic release of resources has already been performed.

  • You must call Dispose explicity on any object implementing IDisposable, otherwise your unmanaged resources will not be disposed. If you don't want to call it explicity, then you must override the Finalize method to call the Dispose method - that is why you will see this frequently:

     class MyClass : IDisposable
     {
        ...
    
        ~MyClass()
        { 
           this.Dispose(false);
        }
    
        public void Dispose()
        {
           this.Dispose(true);
           GC.SuppressFinalize(this);
        }
    
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            { /* dispose managed stuff also */ }
    
            /* but dispose unmanaged stuff always */
        }
     }
    

How to correctly calculate the height of a table

How do you calculate the height of a flexgrid table in VB6 so that it only contains the number of filled rows.

Currently

myFlexGrid.Height = (myFlexGrid.CellHeight * myFlexGrid.Rows) ' paraphrased from code

comes out at about 3 pixels short per line. Adding in the magic number is a bit hackish and would like to accomplish this without having to resort to that.

Update: To complicate matters it also needs to handle multiline cells.

From stackoverflow
  • You need to go

    Me.MSFlexGrid1.Height = (Me.MSFlexGrid1.CellHeight) * (Me.MSFlexGrid1.Rows + Me.MSFlexGrid1.FixedRows) + 30

    The 30 is to make it two pixels longer to show the black border running around the flexgrid.

    Also disabling the vertical scrollbar helps as well.

    graham.reeds : Actually the 30 is not correct from what I can find: If a user is running in 120dpi mode then 12 twips is equal to 1 pixel. But this adding of a semi-arbitary number is what I am trying to avoid.
    graham.reeds : I've also just found it needs to handle multiline cells.
    RS Conley : Unless the control explicitly supports an autoheight function or exposes the values of the height of every UI element you will not be able to avoid using magic numbers. This is because controls are designed as black boxes. It looks like your logic is going to get complex here I suggest wrapping the flexgrid inside of a control class and add the autoheight function in there so the code in your main routines remains clean.
  • RS Coneley is close, but here is the correct way that accounts for all DPI settings:

    Me.MSFlexGrid1.Height = Me.MSFlexGrid1.CellHeight _
                          * (Me.MSFlexGrid1.Rows + Me.MSFlexGrid1.FixedRows) _
                          + (Screen.TwipsPerPixelY * 2)
    
  • This is the final code I came up with

        For i = 0 To fgrComments.Rows - 1
            'Set MSFlexGrid to appropriate Cell
            myFlexGrid.Row = i
    
            'Set textbox to match the selected cell
            txtSizer.Width = myFlexGrid.ColWidth(2)
            txtSizer.Font = myFlexGrid.Font
            txtSizer.Text = myFlexGrid.Text
    
            'Call API to determine how many lines of text are in text box
            lLinesOfText = SendMessage(txtSizer.hwnd, EM_GETLINECOUNT, 0&, 0&)
    
            ' Update the running values
            lTotalNumberOfRows = lTotalNumberOfRows + lLinesOfText
            lCurrentHeight = lCurrentHeight + myFlexGrid.CellHeight
        Next i
    
        ' resize the grid
        Dim iSpacers As Integer
        iSpacers = Screen.TwipsPerPixelY * lTotalNumberOfRows
        myFlexGrid.Height = lCurrentHeight + iSpacers
    

    You will need to Declare the SendMessage (see here to see how) and the value of EM_GETLINECOUNT, but you should be able to do that yourself:-)

    It doesn't remove the magic numbers but it does rationalise them which is close enough for me.

studying nhibernate critieria queries

Is there any other site for studying critieria queries like http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/querycriteria.html

From stackoverflow

Best way to write a custom gauge control in WPF?

I need to write a gauge control in WPF for a project at work. By gauge control, I mean something akin to a traditional car speedometer: a circular face with numbers and ticks around the circumference, and a needle pointing to the current value. Although I could get my employer to purchase a third-party control, or even find a free one somewhere, I’d still like to write it myself, for curiosity’s sake more than anything else.

My first thought was to ‘skin’ an existing control using a template, something like a ProgressBar for example as it has Minimum, Maximum and Value properties. However, I don’t think this will offer me the flexibility that I need.

I’d like to animate the needle that points to the current value, so that when the gauge’s value changes the needle moves from the old value to the new value. I figured the easiest way to do this would be to have some kind of shape or geometry representing the needle, and then apply a RotateTransform of the relevant number of degrees to get the needle to point to the correct value. The animation’s To property would be set to the ‘value degrees’ property via binding.

It seems to me that there are three basic approaches I could take:

Use one custom FrameworkElement to represent the entire gauge
I could derive from FrameworkElement, override its OnRender method, then use the DrawingContext to draw both the gauge face and the needle. This would mean that I could no longer animate the needle directly using a RotateTransform, but would instead have to redraw the entire gauge every time the value changes. This seems inefficient to me, as the gauge face represents the bulk of the drawing code but would change very rarely. However, this approach is the most lightweight in terms of the number of elements used.

Use two custom FrameworkElements, one for the face and one for the needle
I’m currently leaning towards this approach. One element would represent the face, the other the needle. This would allow me to target the needle element with the RotateTransform. The gauge control would then consist of three elements: the face, the needle, and a Panel container to hold both of them (ie. Canvas, Grid, whatever). So three elements instead of one, hence not as lightweight as the first approach.

Use DrawingVisuals to draw the face and needle
I’ve also read about the DrawingVisual class, but I’m a bit confused as to why anyone would use this as opposed to deriving from FrameworkElement and overriding OnRender, given that DrawingVisual must be hosted in a custom FrameworkElement anyway. It would seem that this approach doesn’t offer any advantages over the second approach, and would require more code, but maybe I’m missing something.

Any thoughts or advice regarding which approach people think is best and why would be most welcome!

From stackoverflow
  • Personally I'd recommend making a CustomControl using the second approach. Unless you are going to be showing more than 1000 of the gauges in view at the same time you aren't going to notice the extra element in your visual tree and I think you'll find it's much easier to make and maintain.

    Steve Rands : This is the best approach given my criteria I think. I wasn't able to write the control in this way for a number of reasons (mainly my lack of experience with WPF to date) so in the end I actually went with approach #1.
  • You could just style a slider control and feed values into it. You should be able to make a slider look like any kind of gauge you need.

    Steve Rands : While this would work in some circumstances it wasn't an approach I could use given my requirements (which maybe I should have clarified in the question). The scale of the gauge needed to be variable (ie. min/max range and number of divisions would change), plus I needed other properties to represent coloured ranges on the gauge and so on. I don't believe I could have achieved this by just styling an exisiting control; I couldn't see a way of representing something like that in markup.

msbuild community task and Svn commit

Hi all,

I'm currently using the tigris open source project MSBuild Community Task and I have some trouble with the SvnCommit Task. I don't really know how to use the Targets attribute I have this line in my project :

<SvnCommit Username="myName" Password="myPsswd" LocalPath="$(myPath)" ToolPath="$(SvnPath)" Targets="myFile.zip"/>

and I have an error : "c:\blabla" - which is a part of $(myPath) - is not a working copy; svn : Can't open file 'c:\blabla.svn\Entries"

If someone has some ideas, they are welcome !

maybe sould I use the RepositoryPath attribute ?

From stackoverflow
  • ok I have found my problem and it's so silly that I really apologize for the noise on this site. by the way if it can help someone who encounters same pb...

    so the problem was my "Target" attribute ! I had to use a ItemGroup : so I add the following lines in my project

    <ItemGroup>
      <ToCommit Include="$(myPath)/myFile.zip" />
    </ItemGroup>
    

    and changed the task :

    <SvnCommit Username="myName" Password="myPsswd" LocalPath="$(myPath)" ToolPath="$(SvnPath)" Targets="@(ToCommit)"/>
    

Is there a way to configure email account on iPhone from code?

Hi,

I'm quite new in iPhone development. I'm interested to configure email account on iPhone from code. Is it possible? Is there any API in SDK to implement this?

Thank in advance for your answers.

Regards, M. Wolniewicz

From stackoverflow
  • Unfortunately, you cannot configure eMail accounts on an unjailbroken iPhone from code.

Passing arguments to the Class Constructor

How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below?

<?php

/*
./index.php
*/

function Object($object)
{
    static $instance = array();

    if (is_file('./' . $object . '.php') === true)
    {
     $class = basename($object);

     if (array_key_exists($class, $instance) === false)
     {
      if (class_exists($class, false) === false)
      {
       require('./' . $object . '.php');
      }

      /*
      How can I pass custom arguments, using the
      func_get_args() function to the class constructor?

      $instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...);
      */

      $instance[$class] = new $class();
     }

     return $instance[$class];
    }

    return false;
}

/*
How do I make this work?
*/

Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */);

/*
./libraries/DB.php
*/

class DB
{
    public function __construct($database, $username, $password, $host = 'localhost', $port = 3306)
    {
     // do stuff here
    }
}

?>
From stackoverflow
  • Instead of your class taking separated parameters I'd have it take an array.

    class DB
    {
        public function __construct(array $params)
        {
            // do stuff here
        }
    }
    

    That way you can pass the direct result of the func_get_args into your constructor. The only problem now is being able to figure out the array key / values.

    If anyone else has any ideas I'd also be delighted to know :)

    Alix Axel : I got the same idea as well but I was curious to know if something like I described could be done.
  • I haven't tried this, but call_user_func_array sounds like you want.

    $thing = call_user_func_array(array($classname, '__construct'), $args);
    

    Have a look in the PHP Documentation.

    Alix Axel : Doesn't work. =\ call_user_func_array(array(new $classname(), '__construct'), $args); This works but then I would be calling the constructor twice.
    staticsan : Try it without new $classname().
    Alix Axel : Fatal error: Non-static method test::__construct() cannot be called statically
    staticsan : Okay, I've got no more ideas. Thanks for being willing to try.
  • $klass = new ReflectionClass($classname);
    $thing = $klass->newInstanceArgs($args);
    

    Although the need to use reflection suggests that you are overcomplicating something in your design. Why do you want to write this function in the first place?

    Alix Axel : I admit this function may seem a bit nonsense but I use it for small stuff where a framework may be too bloated. And since it acts as an "autoloader", object constructor and singleton container it does the job perfectly.
    Alix Axel : BTW, that Reflection class is really handy, is there any crash course available on the new features of PHP 5.3? I checked the PHP manual but is it me or it is lacking a lot of documentation?
    troelskn : It's not you: The documentation is rather sparse on that. You'll have to do with http://www.php.net/oop5.reflection. Also, it has been around since 5.1 (or is it 5.0?), so it's not a new feature of 5.3