Archive

Archive for February, 2012

Dispatcher in WPF

February 21, 2012 2 comments

Consider the following program

MainWindow.xaml
   1:  <Window x:Class="DispatcherTrial.MainWindow"
   2:          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   3:          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   4:          Title="MainWindow" Height="350" Width="525">
   5:      <Grid>
   6:          <Grid.RowDefinitions>
   7:              <RowDefinition/>
   8:              <RowDefinition/>
   9:          </Grid.RowDefinitions>
  10:          <Button Name="MyButton" Content="Click Here" 
                             Click="MyButton_Click"></Button>
  11:          <TextBlock Grid.Row="1" Name="myText"></TextBlock>
  12:      </Grid>
  13:  </Window>
MainWindow.xaml.cs
namespace DispatcherTrial
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MyButton_Click(object sender, RoutedEventArgs e)
        {
            Thread myThread = new Thread(DisplayTime);
            myThread.Start();
        }

        private void DisplayTime()
        {
            myText.Text = DateTime.Now.ToString();
        }
    }
}

The code is fairly simple. Grid having two rows, one containing button control and other having a TextBlock. In the click of event of button, I have initialized a new thread. Assigned to that thread is method called “DisplayTime”. Inside “DisplayTime” method, I am assigning the current time to the textblock control. All in all , I am trying to update the UI from code which is running on a separate thread. Ideally the code should run fine but it doesn’t. It throws an exception of type :- InvalidOperationException. And following is the error message : The calling thread cannot access this object because a different thread owns it.

I guess the error description is verbose enough to tell us what’s wrong in the above implementation. We simply cannot update the UI from a seperate thread. To understand more on this consider the following code snippet :

   1:  [STAThread]
   2:  static void Main()
   3:  {
   4:         Application app = new Application();
   5:         Window win = new Window();
   6:         win.Show();
   7:         app.Run();
   8:  }

The main method here is tagged with “STAThread” attribute. STA stands for “Single Threaded Apartment” model of programming. What STA states(or enforces) is that only one thread at a time will be executing our code and it will always be the same thread. All our Winform based application runs on STA model. Indeed one thread controlling the complete application looks like a big constraint and WPF people actually decided to move away from this model by opting an all together different approach. But the plan was abandoned because of various compatibility issues with other already existing applications. So our WPF applications too run on STA model. The thread the controls the application is commonly known as UIThread. “Dispatcher” concept is a mechanism introduced in WPF , with the help of which developer can have more explicit control on this UI thread as of what executes when. We will look into this in more details in the remaining section of this article. But before we take a deep dive, just try to keep in mind the below mentioned points about STA model.

  • Thread that creates a given WPF application also own it and its not possible for any other thread to interact with these elements.
  • In practice entire WPF application runs of single thread and its this thread that owns all the elements in the application.

Dispatcher Concept

As the name implies, the dispatching system is responsible for listening to various kinds of messages and making sure that any object that needs to be notified of that message is notified on the UI thread.

The classes responsible for “Dispatcher” concept are : DispatcherObject and Dispatcher. Actually its the “Dispatcher” class which provides the core implementation of dispatching mechanism. But its the “DispatcherObject” class which exposes a public property called “Dispatcher” , through which we can access the current instance of “Dispatcher” class. Have a look at the following class hierarchy diagram :

image

From the above picture its evident that almost every single entity in WPF derives from the “DispatcherObject” class. Following is the internal implementation of “DispatcherObject” class.

   1:  public abstract class DispatcherObject
   2:  {
   3:      // Fields
   4:      private Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;
   5:   
   6:      // Methods
   7:      protected DispatcherObject()
   8:      {
   9:      }
  10:   
  11:       public bool CheckAccess()
  12:      {
  13:          bool flag = true;
  14:          Dispatcher dispatcher = this._dispatcher;
  15:          if (dispatcher != null)
  16:          {
  17:              flag = dispatcher.CheckAccess();
  18:          }
  19:          return flag;
  20:      }
  21:   
  22:      internal void DetachFromDispatcher()
  23:      {
  24:          this._dispatcher = null;
  25:      }
  26:   
  27:       public void VerifyAccess()
  28:      {
  29:          Dispatcher dispatcher = this._dispatcher;
  30:          if (dispatcher != null)
  31:          {
  32:              dispatcher.VerifyAccess();
  33:          }
  34:      }
  35:   
  36:      // Properties
  38:      public Dispatcher Dispatcher
  39:      {
  40:          get
  41:          {
  42:              return this._dispatcher;
  43:          }
  44:      }
  45:  }
  46:

“DispatcherObject” class offers a public accessor property called “Dispatcher” using which we can access the current instance of “Dispatcher” class. Speaking about “Dispatcher” class, it is responsible for managing the work that takes place in our WPF application.Its this class which owns the application thread and internally it maintains a queue of work items. As the WPF application runs , Dispatcher class accepts incoming requests and executes them one at a time. In short dispatcher is an object which receives messages and delivers it to the correct object for further processing. Dispatcher class is pretty dense with lots of properties and methods. Going into the depth of Dispatcher class is beyond the scope of this article. One final thing on dispatcher class is that a given application can have only one instance of dispatcher class( as the application runs on single thread) , so Dispatcher class implements the very famous “Singleton” pattern. Because of that its impossible to create an instance of Dispatcher class in our custom code. Only with the help of public property “Dispatcher” offered by “DispatcherObject” that we can invoke members defined inside the “Dispatcher” class. Dispatcher class is instantiated as soon as any class which derives from “DispatcherObject” is accessed. All further request are processed by this newly created instance.

Coming back to “DispatcherObject” class , it offers two methods namely CheckAccess and VerifyAccess.

  • CheckAccess : Determines whether the calling thread has access to this DispatcherObject. Only possible return values are true and false.
  • VerifyAccess : VerifyAccess is more stringent compared to CheckAccess. It checks whether the calling thread is the one which created the DispatcherObject. If not it throws “InvalidOperationAccess” exception. Getting back to the example which I gave in the beginning, in that we were trying to update the UI through code which was running on a different thread. Internally VerifyAcess is invoked and once it verifies that calling code is different from the one which controls the application, it throws the “InvalidOperationError” exception.

DispatcherPriority

I have spoken so much on the classes which enable dispatching scenario in WPF. But at the end of the day WPF works on STA model. So how does this whole “Dispatcher” stuff going to help us ? As mentioned before , Dispatcher maintains an internal queue of work items and it process each work items one after the other. Each work item in the queue is has its associated priority. Items are executed relatively to each other on the basis of their priority values. Items with high priority value will be executed before any other items with low priority values. Possible values for the priority field is represented by an enum called “DispatcherPriority”.

   1:  public enum DispatcherPriority
   2:  {
   3:      ApplicationIdle = 2,
   4:      Background = 4,
   5:      ContextIdle = 3,
   6:      DataBind = 8,
   7:      Inactive = 0,
   8:      Input = 5,
   9:      Invalid = -1,
  10:      Loaded = 6,
  11:      Normal = 9,
  12:      Render = 7,
  13:      Send = 10,
  14:      SystemIdle = 1
  15:  }

Now as a WPF programmer, we can push our custom time consuming logic into the queue maintained by the “Dispatcher” class and associate a lower priority value to that work item. Based on the value of priority field the corresponding code will be executed at the specified interval. Important thing to note here is that all the work is still being done by the UIthread, its just that with the help of DispatcherPriority we have prioritized our tasks. Ideally its recommended to give priority values less then 7(render) to the custom logic that we wish to execute with the help of Dispatcher. Most often priority value “Background” is used for application specific custom logic. MS Word spell check is implemented with the help of this mechanism and priority value is “ApplicationIdeal”. Following is the modified code for the example which I have provided in the beginning of the article:

   1:  namespace DispatcherTrial
   2:  {
   3:      /// <summary>
   4:      /// Interaction logic for MainWindow.xaml
   5:      /// </summary>
   6:      public partial class MainWindow : Window
   7:      {
   8:          public MainWindow()
   9:          {
  10:              InitializeComponent();
  11:          }
  12:   
  13:          private void MyButton_Click(object sender, RoutedEventArgs e)
  14:          {
  15:              this.Dispatcher.BeginInvoke(new Action(this.DisplayTime)
                                           , DispatcherPriority.Background);
  16:          }
  17:   
  18:          private void DisplayTime()
  19:          {
  20:              myText.Text = DateTime.Now.ToString();
  21:          }
  22:      }
  23:  }

”BeginInvoke” is a member exposed by the “Dispatcher” class. BeginInvoke adds the delegate to the Dispatcher’s event queue but gives you the opportunity to specify a lower priority for it. This ensures that the Dispatcher processes all loading and rendering events
before executing the delegate that loads the data. This allows the control or window to be displayed and rendered immediately, whilst the data waits in the background to be loaded.

_______________________________________________________________________________________________

Proper use of threads can greatly increase the responsiveness of your WPF applications. Unfortunately, you can’t update any UI controls from a thread that doesn’t own the control. In .NET 2.0, you used Control.Invoke(). Now, we’ve got something similar but more powerful – the Dispatcher. This tutorial will explain what the Dispatcher is and how to use it.

First of all, you need to know where the Dispatcher lives. Every Visual (Button, Textbox, Combobox, etc.) inherits from DispacterObject. This object is what allows you to get a hold of the UI thread’s Dispatcher.

The Dispatcher is why you can’t directly update controls from outside threads. Anytime you update a Visual, the work is sent through the Dispatcher to the UI thread. The control itself can only be touched by it’s owning thread. If you try to do anything with a control from another thread, you’ll get a runtime exception. Here’s an example that demonstrates this:

public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = “A Checkbox”;

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate()
{
myCheckBox.IsChecked = true;
}
));

thread.Start();
}
}
This code creates a Checkbox, then creates a thread which tries to change the checked state. This will fail because the Checkbox was created on a different thread than the one trying to modify it. If you run this code, you’ll end up with this exception:

The calling thread cannot access this object because a different thread owns it.
So the question is, how do you update the Checkbox from this thread? Fortunately, the Dispatcher gives us the ability to Invoke onto its thread. Invoking probably looks really familiar if you’ve programmed in .NET 2.0. We actually have an in-depth tutorial on invoking that you might want to read. Below is code using the Dispatcher that will run and update the Checkbox without throwing an exception.

public Window1()
{
InitializeComponent();

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = “A Checkbox”;

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate()
{
myCheckBox.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
myCheckBox.IsChecked = true;
}
));
}
));

thread.Start();
}
Now we’ve introduced the Dispatcher object. The call to Invoke needs to take a few pieces of information. First is the priority you’d like your work executed with. Next is the delegate that contains the work you actually want to do. If your delegate takes parameters, the Invoke call will also accept an Object or Object[] to pass into the delegate function. It will also accept a timespan that limits the amount of time the Invoke call will wait to execute your code.

The call to Invoke will block until your function has been executed. Depending on the priority you’ve set, this might take a while. The Dispatcher also has the ability to invoke code asynchronously using BeginInvoke. Let’s look at the same example using BeginInvoke.

public Window1()
{
InitializeComponent();

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = “A Checkbox”;

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate()
{
System.Windows.Threading.DispatcherOperation
dispatcherOp = myCheckBox.Dispatcher.BeginInvoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
myCheckBox.IsChecked = true;
}
));

dispatcherOp.Completed += new EventHandler(dispatcherOp_Completed);
}
));

thread.Start();
}

void dispatcherOp_Completed(object sender, EventArgs e)
{
Console.WriteLine(“The checkbox has finished being updated!”);
}
BeginInvoke takes many of the same arguments as Invoke, but now returns a DispatcherOperation that lets you keep track of the progress of your function. In this case, I simply hooked the Completed event that notifies me when the work has been completed. The DispatcherOperation object also lets you control the Dispatcher by changing its priority or aborting it all together.

As I mentioned above, we can limit the amount of time an Invoke is allowed to take my passing the Invoke call a TimeSpan structure. Here’s an example that will wait 1 second for the queued function to complete:

public Window1()
{
InitializeComponent();

CheckBox myCheckBox = new CheckBox();
myCheckBox.Content = “A Checkbox”;

System.Threading.Thread thread = new System.Threading.Thread(
new System.Threading.ThreadStart(
delegate()
{
myCheckBox.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.SystemIdle,
TimeSpan.FromSeconds(1),
new Action(
delegate()
{
myCheckBox.IsChecked = true;
}
));
}
));

thread.Start();
}
Unfortunately, there’s no way to determine if the invoke finished or timed out from the outside. You can always put code inside the invoked function to determine if it executed.

All right, so we’ve got our dispatchers working and code is being executed where it’s supposed to be. Invokes, however, are kind of an expensive process. What happens when your controls are being updated from both external threads and the main UI thread. How do you know if you’re supposed to use Invoke? The Dispatcher object provides a function that tells you whether or not you have to use Invoke. In WinForms you call InvokeRequired on the actual control. In WPF, you call CheckAccess() on the Dispatcher object. CheckAccess() returns a boolean indicating whether or not you can modify the control without Invoking.

if (!myCheckBox.Dispatcher.CheckAccess())
{
myCheckBox.Dispatcher.Invoke(
System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
myCheckBox.IsChecked = true;
}
));
}
else
{
myCheckBox.IsChecked = true;
}
So now, before I invoke, I check to see if I even need to. If I do, I invoke the function, if I don’t, I simply update the control directly.

As you can see, the Dispatcher provides a great deal of flexibility over the WinForms Invoke. There’s a lot about WPF’s dispatching model that we didn’t touch in this tutorial. The System.Windows.Threading namespace contains a lot more useful objects that extends the power of the dispatcher even further. If you’ve got questions or have found crazy uses for the Dispatcher, leave them in the comments.

Categories: WPF Tags:

UI Thread, Dispatchers, Background Workers & Async Network Programming

February 5, 2012 1 comment

Both Silverlight and WPF have the concept of a UI thread. Whenever you tie that thread up, you make your application unresponsive. In Silverlight, if you’re on a page with other plug-ins, you make all the plug-ins unresponsive. (It’s actually per-process, but most modern browsers separate processes by tabs)

Async Network Calls

In order to keep from tying up the UI thread, you have to perform long-running processes on another thread. Often, but not always, those processes are network calls. In Silverlight, all network calls are async with no provision to handle them any other way. This lets you off the hook threading-wise, but requires that you understand how to chain those calls, and how to deal with libraries that have IAsyncResult callbacks that return on different threads.
TestServiceClient client = new TestServiceClient();client.DoSomethingSlowCompleted+= (s, ea) =>{// do something with the results here
Debug.WriteLine(ea.Result);
};
client.DoSomethingSlowAsync();

Background Worker

For other processes, the BackgroundWorker is a great, simple, way to do some background work while reporting progress to the UI. It takes all the dispatching work away, so you can feel free to manipulate the UI from the ProgressChanged and RunWorkerCompleted events. Do not touch the UI from the DoWork event, as that is actually running on a separate thread.

private BackgroundWorker _worker = new BackgroundWorker();private void RunLongProcess(){_worker.WorkerReportsProgress = true;ProgressBar.Minimum = 0;ProgressBar.Maximum = 100;
_worker.DoWork += (s, e) =>
{
for (int i = 0; i < 100; i++)
{
// simulate long-running work
System.Threading.Thread.Sleep(500);
((BackgroundWorker)s).ReportProgress(i+1);
}
};

_worker.ProgressChanged += (s, e) => {
// this is on the UI thread, so you can update UI from here.
ProgressBar.Value = e.ProgressPercentage;
};

_worker.RunWorkerCompleted += (s, e) => {
// clean up after your stuff, yes, you can touch UI here.
};
_worker.RunWorkerAsync();
}

Of course, knowing how to set up event handlers using lambda expressions is always helpful 🙂

Dispatcher

Sometimes, you spin off a thread of your own, or you have to deal with some of the crufty stacks where the callbacks come back on a different thread from the one that created the call. In those cases, you need to use a dispatcher to make a call back to the UI thread.

If the code is on a page, you can call the dispatcher property and pass it a function to execute (yes, more lambda in this example).

private void UpdateUI(){Dispatcher.BeginInvoke(() =>{ProgressBar.Value = 50;});}

But, if the code is in some sort of non-UI class, it gets more complex. You can do it this way, using a dummy control (like we did in Silverlight 2):

TextBlock _dispatcherObject = new TextBlock();private void UpdateUINasty() // avoid this approach unless it’s all you’ve got{_dispatcherObject.Dispatcher.BeginInvoke(() =>{SomePage.ProgressBar.Value = 50; });}

This example assumes the object itself was created on the UI thread. The better way is to use the Deployment object:

private void UpdateUINotSoNasty(){Deployment.Current.Dispatcher.BeginInvoke(() =>{SomePage.ProgressBar.Value = 50;});}

That’s better. Definitely the recommended approach for recent versions of Silverlight, including Windows Phone 7.

Timers

What about when you need to run something on a timer? The normal timer classes require manual dispatching to do any UI updates. However, Silverlight and WPF both have the DispatcherTimerclass that handles all that for you.

private void StartTimer(){DispatcherTimer timer = new DispatcherTimer();timer.Tick += (s, e) =>{
// do some very quick work here update the UI

StatusText.Text = DateTime.Now.Second.ToString();
};

timer.Interval = TimeSpan.FromSeconds(1);
timer.Start();
}

Of course, realize that what you’re doing here is interrupting the UI thread, not really running anything on a separate thread. It’s not suitable for anything long-running and cpu-intensive, but rather something where you need to execute on a regular interval. Clock UI updates are a perfect example.

Threads

In general, I discourage folks from spinning off real threads. Very few people understand how to efficiently work with threads, so even if you’re a threading genius, the person coming in after you probably isn’t. In most cases, the Background Worker will provide you with what you need.

Silverlight doesn’t yet have it, but the Parallel Tasking support built into .NET 4 can really help you out should you really need to do more than two things at once. Definitely check it out.

Conclusion

Threading in Silverlight and WPF is a little trickier than some other technologies, because you have to worry about the UI thread. My intention here was to both inform you that this trickiness exists, and then show some ways of dealing with it.

Using Statement


Defines a scope, outside of which an object or objects will be disposed.

using (Font font1 = new Font(“Arial”, 10.0f))
{
}

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement theIDisposable interface. This interface provides the Dispose method, which should release the object’s resources.

A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement.

using System;

class C : IDisposable
{
     public void UseLimitedResource()
     {
         Console.WriteLine(“Using limited resource…”);
     }

     void IDisposable.Dispose()
     {
         Console.WriteLine(“Disposing limited resource.”);
     }
}

class Program
{
    static void Main()
    {
      using (C c = new C())
      {
        c.UseLimitedResource();
      }
      Console.WriteLine(“Now outside using statement.”);
      Console.ReadLine();
    }
}

Output:
Using limited resource…
Disposing limited resource.
Now outside using statement.

Categories: C# Tags:

MVC, MVP, MVVM


The goal of this article is to clearly explain the differences between these 3 architectures.

Common Elements

First, the let’s define common elements.  All 3 of the architectures are designed to separate the view from the model.

Model

  • Domain entities & functionality
  • Knows only about itself and not about views, controllers, etc.
  • For some projects, it is simply a database and a simple DAO
  • For some projects, it could be a database/file system, a set of entities, and a number of classes/libraries that provide additional logic to the entities (such as performing calculations, managing state, etc)

Implementation: Create classes that describe your domain and handle functionality.  You probably should end up with a set of  domain objects and a set of classes that manipulate those objects.

View

  • Code that handles the display
  • Note that view related code in the codebehind is allowed (see final notes at the bottom for details)

Implementation:  HTML, WPF, WindowsForms, views created programmatically – basically code that deals with display only.

Differences between Presenters, ViewModels and Controllers

This is the tricky part.  Some things that Controllers, Presenters, and ViewModels have in common are:

  • Thin layers
  • They communicate with the model and the view

The features of each.

Presenter (Example: WinForms)

  • 2 way communication with the view
  • View Communication: The view communicates with the presenter by directly calling functions on an instance of the presenter.  The presenter communicates with the view by talking to an interface implemented by the view.
  • There is a single presenter for each view

Implementation:

  • Every view’s codebehind implements some sort of IView interface.  This interface has functions like displayErrorMessage(message:String), showCustomers(customers:IList<Customer>), etc.  When a function like showCustomers is called in the view, the appropriate items passed are added to the display.  The presenter corresponding to the view has a reference to this interface which is passed via the constructor.
  • In the view’s codebehind, an instance of the presenter is referenced.  It may be instantiated in the code behind or somewhere else.  Events are forwarded to the presenter  through the codebehind.  The view never passes view related code (such as controls, control event objects, etc) to the presenter.

ViewModel (Example: WPF)

  • 2 way communication with the view
  • The ViewModel represents the view.  This means that fields in a view model usually match up more closely with the view than with the model.
  • View Communication:  There is no IView reference in the ViewModel.  Instead, the view binds directly to the ViewModel.  Because of the binding, changes in the view are automatically reflected in the ViewModel and changes in the ViewModel are automatically reflected in the view.
  • There is a single ViewModel for each view

Implementation:

  • The view’s datacontext is set to the ViewModel.  The controls in the view are bound to various members of the ViewModel.
  • Exposed ViewModel proproperties implement some sort of observable interface that can be used to automatically update the view (With WPF this is INotifyPropertyChanged; with knockoutjs this is done with the functions ko.observable() and ko.observrableCollection())

Controller (Example: ASP.NET MVC Website)

  • The controller determines which view is displayed
  • Events in the view trigger actions that the controller can use to modify the model or choose the next view.
  • There could be multiple views for each controller
  • View Communication:
    • The controller has a method that determines which view gets displayed
    • The view sends input events to the controller via a callback or registered handler.  In the case of a website, the view sends events to the controller via a url that gets routed to the appropriate controller and controller method.
    • The view receives updates directly from the model without having to go through the controller.
      • Note: In practice, I don’t think this particular feature of MVC is employed as often today as it was in the past.  Today, I think developers are opting for MVVM (or MVP) over MVC in most situations where this feature of MVC would have been used.  Websites are a situation where I think MVC is still a very practical solution.  However, the view is always disconnected from the server model and can only receive updates with a request that gets routed through the controller.  The view is not able to receive updates directly from the model.

Implementation (for web):

  • A class is required to interpret incoming requests and direct them to the appropriate controller.  This can be done by just parsing the url.  Asp.net MVC does it for you.
  • If required, the controller updates the model based on the request.
  • If required, the controller chooses the next view based on the request.  This means the controller needs to have access to some class that can be used to display the appropriate view.  Asp.net MVC provides a function to do this that is available in all controllers.  You just need to pass the appropriate view name and data model.


.

MVVM and MVP implementation seem pretty straightforward but MVC can be a little confusing.  The diagram below from Microsoft’s Smart Client Factory documentation does a great job at showing MVC communication.  Note that the controller chooses the view (ASP.NET MVC) which is not shown in this diagram.  MVVM interactions will look identical to MVP (replace Presenter with ViewModel).  The difference is that with MVP, those interactions are handled programmatically while with MVVM, they will be handled automatically by the data bindings.

 

 General rules for when to use which?

MVP

  • Use in situations where binding via a datacontext is not possible.
  • Windows Forms is a perfect example of this.  In order to separate the view from the model, a presenter is needed.  Since the view cannot directly bind to the presenter, information must be passed to it view an interface (IView).

MVVM

  • Use in situations where binding via a datacontext is possible.  Why?  The various IView interfaces for each view are removed which means less code to maintain.
  • Some examples where MVVM is possible include WPF and javascript projects using Knockout.

MVC

  • Use in situations where the connection between the view and the rest of the program is not always available (and you can’t effectively employ MVVM or MVP).
  • This clearly describes the situation where a web API is separated from the data sent to the client browsers.  Microsoft’s ASP.NET MVC is a great tool for managing such situations and provides a very clear MVC framework.

Final notes

  • Don’t get stuck on semantics.  Many times, one of your systems will not be purely MVP or MVVM or MVC.  Don’t worry about it.  Your goal is not to make an MVP, MVVM, or MVC system.  Your goal is to separate the view, the model, and the logic that governs both of them. It doesn’t matter if your view binds to your ‘Presenter’, or if you have a pure Presenter mixed in with a bunch of ViewModels.  The goal of a maintainable project is still achieved.
  • Some evangelists will say that your ViewModels (and Presenters) must not make your model entities directly available for binding to the view.   There are definitely situations where this is a bad thing.  However, don’t avoid this for the sake of avoiding it.  Otherwise, you will have to constantly be copying data between your model and ViewModel.  Usually this is a pointless waste of time that results in much more code to maintain.
  • In line with the last point, if using WPF it makes sense to implement INotifyPropertyChanged in your model entities.  Yes, this does break POCO but when considering that INotifyPropertyChanged adds a lot of functionality with very little maintenance overhead , it is an easy decision to make.
  • Don’t worry about “bending the rules” a bit so long as the main goal of a maintainable program is achieved
  • Views
    • When there is markup available for creating views (Xaml, HTML, etc), some evangelists may try to convince developers that views must be written entirely in markup with no code behind.  However, there are perfectly acceptable reasons to use the code behind in a view if it is dealing with view related logic.  In fact, it is the ideal way to keep view code out of your controllers, view models, and  presenters.  Examples of situations where you might use the code behind include:
      • Formatting a display field
      • Showing only certain details depending on state
      • Managing view animations
    • Examples of code that should not be in the view
      • Sending an entity to the database to be saved
      • Business logic
Categories: C#, WPF Tags: , ,

Delegate in WPF


 

Introduction

In this article we will first try to understand what problem delegate solves, we will then create a simple delegate and try to solve the problem. Next we will try to understand the concept of multicast delegates and how events help to encapsulate delegates. Finally we understand the difference between events and delegates and also understand how to do invoke delegates asynchronously.

Once we are done with all fundamentals we will summarize the six important uses of delegates.

Abstraction problems of methods and functions

Before we move ahead and we talk about delegates let’s try to understand what problem does delegate solve. Below is a simple class named ‘ClsMaths’ which has a simple ‘Add’ function. This class ‘ClsMaths’ is consumed by a simple UI client. Now let’s say over a period of time you add subtraction functionality to the ‘ClsMaths’ class, your client need to change accordingly to accommodate the new functionality.
In other words addition of new functionality in the class leads to recompiling of your UI client.

In short the problem is that there is a tight coupling of function names with the UI client. So how can we solve this problem?. Rather than referring to the actual methods in the UI / client if we can refer an abstract pointer which in turn refers to the methods then we can decouple the functions from UI.
Later any change in the class ‘ClsMath’ will not affect the UI as the changes will be decoupled by the Abstract pointer. This abstract pointer can be defined by using delegates. Delegates define a simple abstract pointer to the function / method.

Ok, now that we have understood the tight coupling problem and also the solution, let’s try to understand how we can define a simple delegate.

How to declare a delegate?

To implement a delegate is a four step process declare, create, point and invoke.

The first step is to declare the delegate with the same return type and input parameters. For instance the below function ‘add’ has two input integer parameters and one integer output parameter.

private int Add(int i,int y)
{
return i + y;
}

So for the above method the delegate needs to be defined in the follow manner below. Please see the delegate keyword attached with the code.

// Declare delegate
public delegate int PointetoAddFunction(int i,int y);

The return type and input type of the delegate needs to be compatible, in case they are not compatible it will show the below error as shown in the image below.

The next step (second step) is to create a delegate reference.

// Create delegate reference
PointetoAddFunction myptr = null;

The third step is to point the delegate reference to the method, currently we need to point the delegate reference to the add function.

// Point the reference to the add method
myptr = this.Add;

Finally we need to invoke the delegate function using the “Invoke” function of the delegate.

// Invoke the delegate
myptr.Invoke(20, 10)

Below figure sums up how the above four step are map with the code snippet.

Solving the abstract pointer problem using delegates

In order to decouple the algorithm changes we can expose all the below arithmetic function through an abstract delegate.

So the first step is to add a generic delegate which gives one output and takes two inputs as shown in the below code snippet.

public class clsMaths
{
public delegate int PointerMaths(int i, int y);
}

The next step is to expose a function which takes in operation and exposes an attached delegate to the UI as shown in the below code snippet.

public class clsMaths
{
public delegate int PointerMaths(int i, int y);

public PointerMaths getPointer(int intoperation)
{
PointerMaths objpointer = null;
if (intoperation == 1)
{
objpointer = Add;
}
else if (intoperation == 2)
{
objpointer = Sub;
}
else if (intoperation == 3)
{
objpointer = Multi;
}
else if (intoperation == 4)
{
objpointer = Div;
}
return objpointer;
}
}

Below is how the complete code snippet looks like. All the algorithm functions i.e. ‘Add’ , ‘Sub’ etc are made private and only one generic abstract delegate pointer is exposed which can be used to invoke these algorithm function.

public class clsMaths
{
public delegate int PointerMaths(int i, int y);

public PointerMaths getPointer(int intoperation)
{
PointerMaths objpointer = null;
if (intoperation == 1)
{
objpointer = Add;
}
else if (intoperation == 2)
{
objpointer = Sub;
}
else if (intoperation == 3)
{
objpointer = Multi;
}
else if (intoperation == 4)
{
objpointer = Div;
}
return objpointer;
}

private int Add(int i, int y)
{
return i + y;
}
private int Sub(int i, int y)
{
return i - y;
}
private int Multi(int i, int y)
{
return i * y;
}
private int Div(int i, int y)
{
return i / y;
}
}

So at the client side the calls becomes generic without any coupling with the actual method names like ‘Add’ , ‘Sub’ etc.

int intResult = objMath.getPointer(intOPeration).Invoke(intNumber1,intNumber2);

Multicast delegates

In our previous example we have see how we can create a delegate pointer to a function or method. We can also create a delegate which can point to multiple functions and methods. If we invoke such delegate it will invoke all the methods and functions associated with the same one after another sequentially.
Below is the code snippet which attaches 2 methods i.e. method1 and method2 with delegate ‘delegateptr’. In order to add multiple methods and function we need to use ‘+=’ symbols. Now if we invoke the delegate it will invoke ‘Method1’ first and then ‘Method2’. Invocation happen in the same sequence as the attachment is done.

// Associate method1
delegateptr += Method1;
// Associate Method2
delegateptr += Method2;
// Invoke the Method1 and Method2 sequentially
delegateptr.Invoke();

So how we can use multicast delegate in actual projects. Many times we want to create publisher / subscriber kind of model. For instance in an application we can have various error logging routine and as soon as error happens in a application you would like to broadcast the errors to the respective components.

Simple demonstration of multicast delegates

In order to understand multicast delegates better let’s do the below demo. In this demo we have ‘Form1’, ‘Form2’ and ‘Form3’. ‘Form1’ has a multicast delegate which will propagate event to ‘Form2’ and ‘Form3’.

At the form level of ‘Form1’ (this form will be propagating events to form2 and form3) we will first define a simple delegate and reference of the delegate as shown in the code snippet below. This delegate will be responsible for broadcasting events to the other forms.

// Create a simple delegate
public delegate void CallEveryOne();

// Create a reference to the delegate
public CallEveryOne ptrcall=null;
// Create objects of both forms

public Form2 obj= new Form2();
public Form3 obj1= new Form3();

In the form load we invoke the forms and attach ‘CallMe’ method which is present in both the forms in a multicast fashion ( += ).

private void Form1_Load(object sender, EventArgs e)
{
// Show both the forms
obj.Show();
obj1.Show();
// Attach the form methods where you will make call back
ptrcall += obj.CallMe;
ptrcall += obj1.CallMe;
}

Finally we can invoke and broadcast method calls to both the forms.

private void button1_Click(object sender, EventArgs e)
{
// Invoke the delegate
ptrcall.Invoke();
}

Problem with multicast delegates – naked exposure

The first problem with above code is that the subscribers (form2 and form3) do not have the rights to say that they are interested or not interested in the events. It’s all decided by ‘form1’.
We can go other route i.e. pass the delegate to the subscribers and let them attach their methods if they wish to subscribe to the broadcast sent by ‘form1’. But that leads to a different set of problems i.e. encapsulation violation.
If we expose the delegate to the subscriber he can invoke delegate, add his own functions etc. In other words the delegate is completely naked to the subscriber.

Events – Encapsulation on delegates

Events help to solve the delegate encapsulation problem. Events sit on top of delegates and provide encapsulation so that the destination source can only listen and not have full control of the delegate object.
Below figure shows how the things look like:-
• Method and functions are abstracted /encapsulated using delegates
• Delegates are further extended to provide broadcasting model by using multicast delegate.
• Multicast delegate are further encapsulated using events.

Implementing events

So let’s take the same example which we did using multicast delegates and try to implement the same using events. Event uses delegate internally as event provides higher level of encapsulation over delegates.
So the first step in the publisher (‘Form1’) we need to define the delegate and the event for the delegate. Below is the code snippet for the same and please do notice the ‘event’ keyword.
We have defined a delegate ‘CallEveryOne’ and we have specified an event object for the delegate called as ‘EventCallEveryOne’.

public delegate void CallEveryone();
public event CallEveryone EventCallEveryOne;

From the publisher i.e. ‘Form1’ create ‘Form2’ and ‘Form3’ objects and attach the current ‘Form1’ object so that ‘Form2’ and ‘Form3’ will listen to the events. Once the object is attached raise the events.

Form2 obj = new Form2();
obj.obj = this;
Form3 obj1 = new Form3();
obj1.obj = this;
obj.Show();
obj1.Show();
EventCallEveryOne();

At the subscriber side i.e. (Form2 and Form3) attach the method to the event listener.

obj.EventCallEveryOne += Callme;

This code will show the same results as we have got from multicast delegate example.

Difference between delegates and events

So what’s really the difference between delegates and events other than the sugar coated syntax of events. As already demonstrated previously the main difference is that event provides one more level of encapsulation over delegates.
So when we pass delegates it’s naked and the destination / subscriber can modify the delegate. When we use events the destination can only listen to it.

Delegates for Asynchronous method calls

One of the other uses of delegates is asynchronous method calls. You can call methods and functions pointed by delegate asynchronously.
Asynchronous calling means the client calls the delegate and the control is returned back immediately for further execution. The delegate runs in parallel to the main caller. When the delegate has finished doing his work he makes a call back to the caller intimating that the function / subroutine has completed executing.

To invoke a delegate asynchronously we need call the ‘begininvoke’ method. In the ‘begininvoke’ method we need to specify the call back method which is ‘CallbackMethod’ currently.

delegateptr.BeginInvoke(new AsyncCallback(CallbackMethod), delegateptr);

Below is the code snippet for ‘CallbackMethod’. This method will be called once the delegate finishes his task.

static void CallbackMethod(IAsyncResult result)
{
int returnValue = flusher.EndInvoke(result);
}

The Second Change Event Example

Suppose you want to create a Clock class that uses events to notify potential subscribers whenever the local time changes value by one second. Here is the complete, documented example:

using System;
using System.Threading;

namespace SecondChangeEvent
{
/* ======================= Event Publisher =============================== */

// Our subject — it is this class that other classes
// will observe. This class publishes one event:
// SecondChange. The observers subscribe to that event.

public class Clock
{
 // Private Fields holding the hour, minute and second
private int _hour;
private int _minute;
private int _second;

 // The delegate named SecondChangeHandler, which will encapsulate
// any method that takes a clock object and a TimeInfoEventArgs
// object as the parameter and returns no value. It’s the
// delegate the subscribers must implement.

public delegate void SecondChangeHandler (
object clock,
TimeInfoEventArgs timeInformation
);

// The event we publish
public event SecondChangeHandler SecondChange;

 // The method which fires the Event
protected void OnSecondChange(
object clock,
TimeInfoEventArgs timeInformation
)
{
// Check if there are any Subscribers
if (SecondChange != null)
{
// Call the Event
SecondChange(clock,timeInformation);
}
}

 // Set the clock running, it will raise an
// event for each new second

public void Run()
{
for(;;)
{
// Sleep 1 Second
Thread.Sleep(1000);

// Get the current time
System.DateTime dt = System.DateTime.Now;

// If the second has changed
// notify the subscribers

if (dt.Second != _second)
{
// Create the TimeInfoEventArgs object
// to pass to the subscribers

TimeInfoEventArgs timeInformation =
new TimeInfoEventArgs(
dt.Hour,dt.Minute,dt.Second);

// If anyone has subscribed, notify them
OnSecondChange (this,timeInformation);
}

// update the state
_second = dt.Second;
_minute = dt.Minute;
_hour = dt.Hour;

}
}
}

// The class to hold the information about the event
// in this case it will hold only information
// available in the clock class, but could hold
// additional state information

public class TimeInfoEventArgs : EventArgs
{
public TimeInfoEventArgs(int hour, int minute, int second)
{
this.hour = hour;
this.minute = minute;
this.second = second;
}
public readonly int hour;
public readonly int minute;
public readonly int second;
}

 /* ======================= Event Subscribers =============================== */

// An observer. DisplayClock subscribes to the
// clock’s events. The job of DisplayClock is
// to display the current time

public class DisplayClock
{
// Given a clock, subscribe to
// its SecondChangeHandler event

public void Subscribe(Clock theClock)
{
theClock.SecondChange +=
new Clock.SecondChangeHandler(TimeHasChanged);

}

 // The method that implements the
// delegated functionality

public void TimeHasChanged(
object theClock, TimeInfoEventArgs ti)
{
Console.WriteLine(“Current Time: {0}:{1}:{2}”,
ti.hour.ToString(),
ti.minute.ToString(),
ti.second.ToString());
}
}

// A second subscriber whose job is to write to a file
public class LogClock
{
public void Subscribe(Clock theClock)
{
theClock.SecondChange +=
new Clock.SecondChangeHandler(WriteLogEntry);

}

// This method should write to a file
// we write to the console to see the effect

// this object keeps no state
public void WriteLogEntry(
object theClock, TimeInfoEventArgs ti)
{
Console.WriteLine(“Logging to file: {0}:{1}:{2}”,
ti.hour.ToString(),
ti.minute.ToString(),
ti.second.ToString());
}
}

/* ======================= Test Application =============================== */

// Test Application which implements the
// Clock Notifier – Subscriber Sample

public class Test
{
public static void Main()
{
// Create a new clock
Clock theClock = new Clock();

// Create the display and tell it to
// subscribe to the clock just created

DisplayClock dc = new DisplayClock();
dc.Subscribe(theClock);

// Create a Log object and tell it
// to subscribe to the clock

LogClock lc = new LogClock();
lc.Subscribe(theClock);

// Get the clock started
theClock.Run();
}
}
}

Summarizing Use of delegates

There are 6 important uses of delegates:-
1. Abstract and encapsulate a method (Anonymous invocation)

This is the most important use of delegates; it helps us to define an abstract pointer which can point to methods and functions. The same abstract delegate can be later used to point to that type of functions and methods. In the previous section we have shown a simple example of a maths class. Later addition of new algorithm functions does not affect the UI code.

2. Callback mechanism
Many times we would like to provide a call back mechanism. Delegates can be passed to the destination and destination can use the same delegate pointer to make callbacks.

3. Asynchronous processing
By using ‘BeginInvoke’ and ‘EndInvoke’ we can call delegates asynchronously. In our previous section we have explained the same in detail.

4. Multicasting – Sequential processing
Some time we would like to call some methods in a sequential manner which can be done by using multicast delegate. This is already explained in the multicast example shown above.

5. Events – Publisher subscriber model
We can use events to create a pure publisher / subscriber model.

Difference between delegates and C++ pointer

C++ pointers are not type safe, in other words it can point to any type of method. On the other hand delegates are type safe. A delegate which is point to a return type of int cannot point to a return type of string.

Why do we need delegates

Simple answer: the code needing to perform the action doesn’t know the method to call when it’s written. You can only call the method directly if you know at compile-time which method to call, right? So if you want to abstract out the idea of “perform action X at the appropriate time” you need some representation of the action, so that the method calling the action doesn’t need to know the exact implementation ahead of time.

For example:

  • Enumerable.Select in LINQ can’t know the projection you want to use unless you tell it
  • The author of Button didn’t know what you want the action to be when the user clicks on it
  • They also make certain designs cleaner (for example, instead of a switch statement where you call different methods, you call the delegate passed in) and easier to understand and allow for extending your code without changing it
  • Delegates are also the basis of the eventing system – writing and registering event handlers without delegates would be much harder than it is with them

Func and Action Delegates

The Func and Action generic delegates were introduced in the .NET framework version 3.5. They provide flexible delegates with generic parameters that can be used for many purposes, including passing lambda expressions to method parameters.

Generic Delegates

The .NET framework version 3.5 introduced two new sets ofgeneric, parameterised delegates named Func and Action. The Func delegate can be used to encapsulate a method that accepts between zero and four arguments and returns a value. The Action delegate also represents methods with zero to fourparameters but differs from Func in that the method must return void.

The new delegates can be used to reduce the number of delegates that you define explicitly. In situations where you would need a delegate that matches one of the predefined Func or Action signatures, you may decide to use the built-in version. You should consider the naming of the delegate however, as “Func” or “Action” may not express your intent as clearly as another name.

One of the key reasons for the introduction of Func and Action is their relationship with lambda expressions. Every lambda expression’s underlying type is one of these generic delegates. This means that lambda expressions can be passed to method parameters of the appropriate type without explicitly creating a delegate. Many of the LINQ standard query operators accept Func arguments to take advantage of this feature.

Func Delegate

There are five variations upon the Func delegate, each allowing a different number of parameters to be represented. In each case, the return value and the parameters are defined as generic types, allowing the types to vary according to the method that the delegate encapsulates. The five signatures are shown below. Note that the return value of the method is always the last element in the list of types.

public delegate TResult Func<TResult>()
public delegate TResult Func<T, TResult>(T arg)
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2)
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3)
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Using Func<TResult>

The most basic variant of Func is Func<TResult>. This delegate represents methods that return a value but have no parameters. We can demonstrate this with the following sample code. In the example, a new delegate is created using ananonymous method. The method returns a double-precision floating-point number containing a tax rate value.

Func<double> taxRate = delegate { return 17.5; };
Console.WriteLine("{0}%", taxRate());   // Outputs "17.5%"

We can create the same functionality using a lambda expression. Any lambda that accepts no arguments and returns a double is of the type Func<double>. To demonstrate, try executing the following:

Func<double> taxRate = () => 17.5;
Console.WriteLine("{0}%", taxRate());   // Outputs "17.5%"

Using Func with Parameters

Func can represent methods with up to four parameters. In the next example a Func delegate is used to reference an anonymous method that accepts three integer arguments and returns a long integer.

Func<int, int, int, long> multiply = delegate(int a, int b, int c) { return a * b * c; };
Console.WriteLine(multiply(2, 3, 4));   // Outputs "24"

Again, the code can be recreated using a lambda expression in place of the anonymous method. In this case, the three parameters are named a, b and c. The parameter types do not need to be included in the lambda expression as they, and the return type, are inferred by the compiler.

Func<int, int, int, long> multiply = (a, b, c) => a * b * c;
Console.WriteLine(multiply(2, 3, 4));   // Outputs "24"

Action Delegate

As with Func, the Action delegate has five variations. These allow the encapsulation of methods that have up to four parameters but do not return a value. Again, all of the parameters are generic types allowing any type to be used for each argument. The five signatures are as follows:

public delegate void Action()
public delegate void Action<T, >(T arg)
public delegate void Action<T1, T2>(T1 arg1, T2 arg2)
public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3)
public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4)

Using Action

The simplest Action delegate is used with methods that accept no parameters and return no values. The following code demonstrates this with an anonymous method that outputs text to the console.

Action showMessage = delegate { Console.WriteLine("Hello, world"); };
showMessage();                  // Outputs "Hello, world"

As with the Func delegates, Action can be used with lambda expressions. The equivalent of the previous example can be created using a statement lambda, as follows:

Action showMessage = () => { Console.WriteLine("Hello, world"); };
showMessage();                  // Outputs "Hello, world"

Using Action with Parameters

As a final example of the basic use of Action, consider the following example. This code uses a single string parameter for the delegate. The parameter accepts a message to be outputted to the console.

Action<string> showMessage = delegate(string msg) { Console.WriteLine(msg); };
showMessage("Hello, world");    // Outputs "Hello, world"

This example can be recreated using a statement lambda that includes a parameter. In this case the string parameter’s type is inferred.

Action<string> showMessage = (msg) => { Console.WriteLine(msg); };
showMessage("Hello, world");    // Outputs "Hello, world"

Using Generic Delegates as Parameter Types

The Func delegate is commonly used as the type for parameters of methods that accept lambda expressions. These include LINQ standard query operators and similar methods that you create in your own projects. We will demonstrate this with this article’s final example.

The following method defines an array containing the names of ten fruits. The method returns a filtered list of these fruits based upon the delegate passed as the only argument. Note that the types assigned to the Func delegate specify that the encapsulated method must receive a single string parameter and return a Boolean value. We could execute the passed method against each fruit string in a for-each loop. However, for simplicity the example uses the “Where” query operator.

private static string[] Fruit(Func<string, bool> filter)
{
    string[] fruit = new string[] { "Apple", "Banana", "Cherry", "Damson", "Elderberry", "Fig", "Grapefruit", "Huckleberry", "Lemon", "Mango" };
    return fruit.Where(filter).ToArray();
}

To test the method, add the following code to the Main method of a console application. This code calls the Fruit method, applying a filter that returns only fruit with a name shorter than six characters. The fruit names are then outputted.

string[] shortFruit = Fruit(f => f.Length < 6);
foreach (string fruit in shortFruit)
    Console.WriteLine(fruit);

/* OUTPUT Apple Fig Lemon Mango */


Categories: WPF Tags:

Garbage Collection in .NET


Garbage Collection in .NET – How it really works

Garbage collection is a process of releasing the memory used by the objects, which are no longer referenced. This is done in different ways and different manners in various platforms and languages. We will see how garbage collection is being done in .NET.Garbage Collection basis
  • Almost every program uses resources such as database connection, file system objects etc. In order to make use of these things some resources should be available to us.
  • First we allocate a block of memory in the managed memory by using the new keyword.
  • Use the constructor of the class to set the initial state of the object.
  • Use the resources by accessing the type’s members
  • At last CLEAR THE MEMORY

But how many times have programmers forgotten to release the memory. Or how many times the programmers try to access the memory which was cleaned.

These two are the serious bugs, which will lead us to memory leak and commonly occurring. In order to overcome these things the concept of automatic memory management has come. Automatic memory management or Automatic garbage collection is a process by which the system will automatically take care of the memory used by unwanted objects (we call them as garbage) to be released. Hurrah… Thanks to Microsoft’s Automatic Garbage collection mechanism.

Automatic Garbage Collection in .NET

When Microsoft planned to go for a new generation platform called .NET with the new generation language called C#, their first intention is to make a language which is developer friendly to learn and use it with having rich set of APIs to support end users as well. So they put a great thought in Garbage Collection and come out with this model of automatic garbage collection in .NET.

They implemented garbage collector as a separate thread. This thread will be running always at the back end. Some of us may think, running a separate thread will make extra overhead. Yes. It is right. That is why the garbage collector thread is given the lowest priority. But when system finds there is no space in the managed heap (managed heap is nothing but a bunch of memory allocated for the program at run time), then garbage collector thread will be given REALTIME priority (REALTIME priority is the highest priority in Windows) and collect all the un wanted objects.

How does Garbage collector locate garbage

When an program is loaded in the memory there will be a bunch of memory allocated for that particular program alone and loaded with the memory. This bunch of memory is called Managed Heap in .NET world. This amount of memory will only be used when an object is to be loaded in to the memory for that particular program.

This memory is separated in to three parts :

  • Generation Zero
  • Generation One
  • Generation Two

Ideally Generation zero will be in smaller size, Generation one will be in medium size and Generation two will be larger.

When we try to create an object by using NEW keyword the system will,

  • Calculate the number of bytes required for the object or type to be loaded in to the managed heap.
  • The CLR then checks that the bytes required to allocate the object are available in the reserved region (committing storage if necessary). IF the object fits, it is allocated at the address pointed to by NextObjPtr.
  • These processes will happen at the Generation zero level.

When Generation Zero is full and it does not have enough space to occupy other objects but still the program wants to allocate some more memory for some other objects, then the garbage collector will be given the REALTIME priority and will come in to picture.

Now the garbage collector will come and check all the objects in the Generation Zero level. If an object’s scope and lifetime goes off then the system will automatically mark it for garbage collection.

Note:

Here in the process the object is just marked and not collected. Garbage collector will only collect the object and free the memory.

Garbage collector will come and start examining all the objects in the level Generation Zero right from the beginning. If it finds any object marked for garbage collection, it will simply remove those objects from the memory.

Here comes the important part. Now let us refer the figure below. There are three objects in the managed heap. If A and C are not marked but B has lost it scope and lifetime. So B should be marked for garbage collection. So object B will be collected and the managed heap will look like this.
But do remember that the system will come and allocate the new objects only at the last. It does not see in between. So it is the job of garbage collector to compact the memory structure after collecting the objects. It does that also. So the memory would be looking like as shown below now.
But garbage collector does not come to end after doing this. It will look which are all the objects survive after the sweep (collection). Those objects will be moved to Generation One and now the Generation Zero is empty for filling new objects.

If Generation One does not have space for objects from Generation Zero, then the process happened in Generation Zero will happen in Generation one as well. This is the same case with Generation Two also.

You may have a doubt, all the generations are filled with the referred objects and still system or our program wants to allocate some objects, then what will happen? If so, then the MemoryOutofRangeException will be thrown.

Dispose

Instead of declaring a Finalizer, exposing a Dispose method is considered as good.

public void Dispose()
{
// all clean up source code here..
GC.SuppressFinalize(this);
}

If we clean up a object, using Dispose or Close method, we should indicate to the runtime that the object is no longer needed finalization, by calling GC.SuppressFinalize() as shown above.

If we are creating and using objects that have Dispose or Close methods, we should call these methods when we’ve finished using these objects. It is advisable to place these calls in a finally clause, which guarantees that the objects are properly handled even if an exception is thrown.

Object.Finalize Method

The Finalize method is used to perform cleanup operations on unmanaged resources held by the current object before the current object is destroyed. The method is protected and therefore is accessible only through this class or through a derived class.

This method is automatically called after an object becomes inaccessible, unless the object has been exempted from finalization by a call to GC.SuppressFinalize. During shutdown of an application domain, Finalize is automatically called on objects that are not exempt from finalization, even those that are still accessible.

Finalize operations have the following limitations:

  • The exact time when the finalizer executes during garbage collection is undefined. Resources are not guaranteed to be released at any specific time, unless calling aClose method or a Dispose method.
  • The finalizers of two objects are not guaranteed to run in any specific order, even if one object refers to the other. That is, if Object A has a reference to Object B and both have finalizers, Object B might have already finalized when the finalizer of Object A starts.
  • The thread on which the finalizer is run is unspecified.
Categories: C# Tags:
%d bloggers like this: