Saturday, 20 October 2018

Understanding Rxjs Observable

What is Reactive Programming?
Reactive programming is programming with asynchronous data streams.

Reactive Extensions for JavaScript (RxJS) is a reactive streams library that allows you to work with asynchronous data streams. RxJS can be used both in the browser or in the server-side using Node.js.

When version 2 of Angular came out, it introduced us to observables. The Observable isn’t an Angular specific feature, but a new standard for managing async data that will be included in the ES7 release. Angular uses observables extensively in the event system and the HTTP service.

What is Observable:
Observables can be defined as a streams of data whose items arrive asynchronously over time.
To use observables, Angular uses a third-party library called Reactive Extensions (RxJS). Observables are a proposed feature for ES 2016, the next version of JavaScript.


You can think of an observable as an array whose items arrive asynchronously over time. Observables help you manage asynchronous data, such as data coming from a backend service. Observables are used within Angular itself, including Angular’s event system and its http client service. To use observables, Angular uses a third-party library called Reactive Extensions (RxJS). 

An Observable by default is unicast. Unicasting means that each subscribed observer owns an independent execution of the Observable. To demonstrate this:

const observable = Rx.Observable.create((observer=> {
    observer.next(Math.random());
    });
    
    // subscription 1
    observable.subscribe((data=> {
      console.log(data); // 0.24957144215097515 (random number)
    });
    
    // subscription 2
    observable.subscribe((data=> {
       console.log(data); // 0.004617340049055896 (random number)
    });

Subject:
While Observables are unicast by design, this can be pretty annoying if you expect that each subscriber receives the same values. Subjects can help us overcome this issue.
Subjects can multicast. Multicasting basically means that one Observable execution is shared among multiple subscribers.

Subjects are like Event Emitters, they maintain a registry of many listeners. When calling subscribe on a Subject it does not invoke a new execution that delivers data. It simply registers the given Observer in a list of Observers.

So how to use Subjects to multicast
Multicasting is a characteristic of a Subject. You don’t have to do anything special to achieve this behavior's. This is a small multicast demonstration:

const subject = new Rx.Subject();

// subscriber 1
subject.subscribe((data) => {
    console.log(data); // 0.24957144215097515 (random number)
});

// subscriber 2
subject.subscribe((data) => {
    console.log(data); // 0.24957144215097515 (random number)
});

subject.next(Math.random());

Nice! Now I got two subscriptions getting the same data. This however is not all that Subjects can do.

Whereas Observables are solely data producers, Subjects can both be used as a data producer and a data consumer. By using Subjects as a data consumer you can use them to convert Observables from unicast to multicast. Here’s a demonstration of that:

const observable = Rx.Observable.create((observer) => {
    observer.next(Math.random());
});

const subject = new Rx.Subject();

// subscriber 1
subject.subscribe((data) => {
    console.log(data); // 0.24957144215097515 (random number)
});

// subscriber 2
subject.subscribe((data) => {
    console.log(data); // 0.24957144215097515 (random number)
});

observable.subscribe(subject);

We pass our Subject to the subscribe function and let it take the values that come out of the Observable (data consuming). All the subscribers to that Subject will then all immediately receive that value.

merge: Turn multiple observables into a single observable.
var source1 = Rx.Observable.interval(100)
    .timeInterval()
    .pluck('interval');
var source2 = Rx.Observable.interval(150)
    .timeInterval()
    .pluck('interval');

var source = Rx.Observable.merge(
    source1,
    source2)
    .take(5);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

// => Next: 100
// => Next: 150
// => Next: 100
// => Next: 150
// => Next: 100
// => Completed

When do we apply forkJoin?
We use it when API requests are independent. It means that they do not depend on each other to complete and can execute in parallel. 
When all observables complete, emit the last emitted value from each. This operator is best used when you have a group of observables and only care about the final emitted value of each. Example link

When do we apply mergeMap/flatMap?
flatMap is an alias for mergeMap. When we need data from the first API request to make requests to the second API. Example link

concat: Concatenates all of the specified observable sequences, as long as the previous observable sequence terminated successfully.

/* Using Observable sequences */
var source1 = Rx.Observable.return(42);
var source2 = Rx.Observable.return(56);

var source = Rx.Observable.concat(source1, source2);

var subscription = source.subscribe(
    function (x) {
        console.log('Next: ' + x);
    },
    function (err) {
        console.log('Error: ' + err);
    },
    function () {
        console.log('Completed');
    });

// => Next: 42
// => Next: 56
// => Completed

empty: Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.

var source = Rx.Observable.empty();

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });
  
// => Completed

catch: Continues an observable sequence that is terminated by an exception with the next observable sequence.

var obs1 = Rx.Observable.throw(new Error('error'));
var obs2 = Rx.Observable.return(42);

var source = Rx.Observable.catch(obs1, obs2);

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

// => Next: 42
// => Completed

zipMerges the specified observable sequences or Promises into one observable sequence by using the selector function, when all observable emit then only emit result as an array. The data emitted by the combined Observable is mapped one by one in order.

/* Without a result selector */
var range = Rx.Observable.range(0, 5);

var source = Rx.Observable.zip(
  range,
  range.skip(1),
  range.skip(2)
);

var subscription = source.subscribe(
  function (x) {
    console.log('Next: %s', x);
  },
  function (err) {
    console.log('Error: %s', err);
  },
  function () {
    console.log('Completed');
  });

// => Next: 0,1,2
// => Next: 1,2,3
// => Next: 2,3,4
// => Completed

map: Apply projection with each value from source. map is an operator that transforms data by applying a function.
// RxJS v6+
import { from } from 'rxjs';
import { map } from 'rxjs/operators';

//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//add 10 to each value
const example = source.pipe(map(val => val + 10));
//output: 11,12,13,14,15
const subscribe = example.subscribe(val => console.log(val));
pipe:
A Pipeable Operator is a function that takes an Observable as its input and returns another Observable. the previous Observable stays unmodified.
   You can use pipes to link operators together. Pipes let you combine multiple functions into a single function. The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
pipe was introduced to RxJS in v5.5 to take code that looked like this:

of(1,2,3).map(x => x + 1).filter(x => x > 2);

and turn it into this
of(1,2,3).pipe(
    map(x => x + 1),
    filter(x => x > 2)
  );

Example :
import { filtermap } from 'rxjs/operators';
const nums = of(12345);

// Create a function that accepts an Observable.
const squareOddVals = pipe(
  filter((nnumber=> n % 2 !== 0),
  map(n => n * n)
);

// Create an Observable that will run the filter and map functions
const squareOdd = squareOddVals(nums);

// Suscribe to run the combined functions
squareOdd.subscribe(x => console.log(x));

filter: Emit values that pass the provided condition
// RxJS v6+
import { from } from 'rxjs';
import { filter } from 'rxjs/operators';

//emit (1,2,3,4,5)
const source = from([1, 2, 3, 4, 5]);
//filter out non-even numbers
const example = source.pipe(filter(num => num % 2 === 0));
//output: "Even number: 2", "Even number: 4"
const subscribe = example.subscribe(val => console.log(`Even number: ${val}`));

takeWhile: Emit values until provided expression is false.
// RxJS v6+
import { of } from 'rxjs';
import { takeWhile } from 'rxjs/operators';

//emit 1,2,3,4,5
const source = of(1, 2, 3, 4, 5);
//allow values until value from source is greater than 4, then complete
const example = source.pipe(takeWhile(val => val <= 4));
//output: 1,2,3,4
const subscribe = example.subscribe(val => console.log(val));
Difference between takeWhile() and filter()
// RxJS v6+
import { of } from 'rxjs';
import { takeWhile, filter } from 'rxjs/operators';

// emit 3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3
const source = of(3, 3, 3, 9, 1, 4, 5, 8, 96, 3, 66, 3, 3, 3);

// allow values until value from source equals 3, then complete
// output: [3, 3, 3]
source
  .pipe(takeWhile(it => it === 3))
  .subscribe(val => console.log('takeWhile', val));

// output: [3, 3, 3, 3, 3, 3, 3]
source
  .pipe(filter(it => it === 3))
  .subscribe(val => console.log('filter', val));

From: convert various other objects and data types into Observables
// RxJS v6+
import { from } from 'rxjs';

//emit array as a sequence of values
const arraySource = from([1, 2, 3, 4, 5]);
//output: 1,2,3,4,5
const subscribe = arraySource.subscribe(val => console.log(val));

of: Converts the arguments to an observable sequence. link
// RxJS v6+
import { of } from 'rxjs';
//emits any number of provided values in sequence
const source = of(1, 2, 3, 4, 5);
//output: 1,2,3,4,5
const subscribe = source.subscribe(val => console.log(val));

switchMap
switchMap is very similar to flatMap, but with a very important distinction.

in short, every time an event comes down the stream, flatMap will subscribe to (and invoke) a new observable without unsubscribing from any other observable created by a previous event. switchMap on the other hand will automatically unsubscribe from any previous observable when a new event comes down the stream.
https://angular-2-training-book.rangle.io/

catchError: Gracefully handle errors in an observable sequence.

combineLatest: combineLatest combines the values from all the Observables passed as arguments. This happens by subscribing to each Observable in order and, whenever any Observable emits, collecting an array of the most recent values from each Observable. So if we pass an observable to the combineLatest operator, the returned Observable will always emit an array of ‘n’ values. Click here for more

dispatchEvent:

Read more https://github.com/Reactive-Extensions/operators




Continue Reading →

Thursday, 18 October 2018

Delegate, Func, Action, Predicate

Delegate is a reference type that holds the reference of a class method. Any method which has the same signature as delegate can be assigned to delegate. Delegate is like function pointer in C++.
To read more delegates-c-sharp.html

Different Flavors of Delegate
  1. Func<TParameter, TOutput>
  2. Action<TParameter>
  3. Predicate<in T>
1- Func is logically similar to base delegate implementation. The difference is in the way we declare. At the time of declaration, we need to provide the signature parameter & its return type.

Func<string, int, int> tempFuncPointer;

Func is always used when you have return object or type from method. If you have void method, you should be using Action.

2- Action is used when we do not have any return type from method. Method with void signature is being used with Action delegate.

Action<string, int> tempActionPointer;

Similar to Func delegate, the first two parameters are the method input parameters. Since we do not have return object or type, all the parameters are considered as input parameters.

3- Predicate is a function pointer for method which returns boolean value. It is used to represent a set of criteria and determine if the argument matches the criteria. Declaration for the same looks like this:

Predicate<Employee> tempPredicatePointer;

Example Code: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TestAppConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Action<int> myAction = new Action<int>(DoSomething);
            myAction(123);           // Prints out "123"
                                     // can be also called as myAction.Invoke(123);

            Func<int, double> myFunc = new Func<int, double>(CalculateSomething);
            Console.WriteLine(myFunc(5));   // Prints out "2.5"


            Predicate<int> myPred = new Predicate<int>(CheckVal);   
            Console.WriteLine(myPred(1));    // Prints out "true"
           
            Console.ReadLine();
        }

        static void DoSomething(int i)
        {
            Console.WriteLine(i);
        }

        static double CalculateSomething(int i)
        {
            return (double)i / 2;
        }

        static bool CheckVal(int i)
        {
            return true;
        }

    }
}

In short:
Action is a delegate (pointer) to a method, that takes zero, one or more input parameters, but does not return anything.
Func is a delegate (pointer) to a method, that takes zero, one or more input parameters, and returns a value (or reference).
Predicate is a special kind of Func often used for comparisons.
Continue Reading →

Thursday, 11 October 2018

C# 6.0 New Features


1- String Interpolation
public string FullName => $"{FirstName} {LastName}";

2- Expression bodied function

        private Employee GetData(int Id) => Id != 0
         ? new Employee
         {
             EmpId = 1,
             EmpName = "Suraj"
         }
         : null;

        public class Employee
        {
            public int EmpId { get; set; }
            public string EmpName { get; set; }

        }

3- Null-conditional operators


var EmpId = emp?.EmpId;
var EmpName = emp?.EmpName ?? "Unspecified";

Continue Reading →

Tuesday, 9 October 2018

JavaScript Inheritance

JavaScript does not have classes unlike other languages. It uses the concept of prototypes and prototype chaining for inheritance.

Let’s implement prototype chaining

//SuperType constructor function
function SuperType(){
    this.name = "Virat"
   }
   
   //SuperType prototype
   SuperType.prototype.getSuperName = function(){
    return this.name
   }
   
   //SubType prototype function
   function SubType(){
    this.age = 26
   }
   
   //Inherit the properties from SuperType
   SubType.prototype = new SuperType();
   
   //Add new property to SubType prototype
   SubType.prototype.getSubAge = function(){
    return this.age;
   }
   
   //Create a SubType object
   var subTypeObj = new SubType();
   console.log(subTypeObj.name); //Output: Virat
   console.log(subTypeObj.age); //Output: 26
   console.log(subTypeObj.getSuperName()); //Output: Virat
   console.log(subTypeObj.getSubAge()); //Output: 26

Above code defines two consructor functions, SuperType and SubType. By default, SubType.prototype has a constructorfunction which points to the constructor function itself and proto property which inherits the default object properties.

//Inherit the properties from SuperType
SubType.prototype = new SuperType();

Now, SubType function has access to all the SuperType properties and methods.

Continue Reading →

Wednesday, 26 September 2018

Angular Code Questions

Q: How to get data from url in Angular 
http://localhost:4200/about/7

const routesRoutes = [
    { path: ''component: DatabindingComponent },
    { path: 'about/:id'component: AboutComponent },
    { path: 'notfound'component: NotfoundComponent },
    { path: '**'redirectTo: 'notfound' }
   ];

export class AboutComponent implements OnInit {
    idstring;  id2string;
    constructor(private routeActivatedRoute) { }
    
    ngOnInit() {
       this.route.params.subscribe((params=> {
       this.id = params.id;
this.id2 = this.route.snapshot.params.id;
      });
    }

Q: Data Binding in Angular

databinding.component.ts
export class DatabindingComponent implements OnInit {
    companystring;
    urlstring;
    name:string;
    constructor() {}
    
    ngOnInit() {
    this.company = 'Dot Net Guru';
    this.url = 'http://www.dotnetguru.in';
    this.name='Suraj';
    }
    
    Greet() {
     console.log(this.name);
     alert('Hi from Angular!');
     }
    }

databinding.component.htm
//Interpolation
<p>{{company}}, {{name}}</p>
<img src='{{imagePath}}'/>
//Property Binding
<a [href]="url">Website</a>
<img [src]='imagePath'/>
<input type="text" [value]="name"/>
//Event Binding
<button type="button" (click)="Greet()">Greet</button>
//Two Way data binding
<input type="text" [(ngModel)]="name"/

Angular attribute binding
<tr><th [attr.colspan]="columnSpan">Employee Details</th></tr>

Angular class binding: https://www.youtube.com/
Angular style binding: https://www.youtube.com/

Q: Directive (If, If-else, loop, switch-case)

dir.component.ts
export class DirComponent implements OnInit {
    numnumber;
    alphabet:string;
    colors=['red','blue','green'];
    
    constructor() {}
    ngOnInit() {
       this.num = 1;
      }
    }

dir.component.html
<p>
<input type="number" [(ngModel)]="num" />
</p>

<h3>ngIf</h3>
<div *ngIf="num%2==0">
Even Number
</div>

<div *ngIf="num%2>0">
Odd Number
</div>

<h3>ngIf..else</h3>
<div *ngIf="num%2==0 then divif; else divelse"></div>
<ng-template #divif>Even Number</ng-template>
<ng-template #divelse>Odd Number</ng-template>

<h3>ngSwitch</h3>
<p>
<input type="text" [(ngModel)]="alphabet" />
</p>

<div [ngSwitch]="alphabet">
<div *ngSwitchCase="'a'">Vowel</div>
<div *ngSwitchCase="'e'">Vowel</div>
<div *ngSwitchCase="'i'">Vowel</div>
<div *ngSwitchCase="'o'">Vowel</div>
<div *ngSwitchCase="'u'">Vowel</div>
<div *ngSwitchDefault>Not Vowel</div>
</div>

<h3>Loop</h3>
<ul>
<li *ngFor="let item of colors; let i=index">
{{i+1}} {{item}}
</li>
</ul>
Output: 

Q: Pipe
<tr *ngFor="let item of emp | orderBy: 'name' : true" >
<td>{{item.name | uppercase}}</td>
<td>{{item.address | lowercase | reverse}}</td>
<td>{{item.joining | date:'dd/MM/yyyy'}}</td>
<td>{{item.salary | currency:'INR'}}</td>
</tr>

Q: Access data from parent to child component

Parent Component
@Component({
    selector: 'app-master',
    templateUrl: './master.component.html',
    styles: []
  })
  export class MasterComponent implements OnInit {
    companystring;
    constructor() {
      this.company = 'Dot Net Tricks';
    }
    ngOnInit() {}
  }

Parnet Component html
<app-details [companyName]="company"></app-details>

Child Component
import { ComponentOnInitInputOutputfrom '@angular/core';

@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styles: []
})
export class DetailsComponent implements OnInit {
  @Input() companyNamestring;
  constructor() { }

  ngOnInit() {}
}

Child Component html
<p>{{companyName}}</p>

Q: Access data from child to parent component

Child Component html
<button type="button" (click)="SendMessage()">Send Msg</button>

Child Component
import {Component,OnInit,Output,EventEmitterfrom '@angular/core';
@Component({
  selector: 'app-details',
  templateUrl: './details.component.html',
  styles: []
})
export class DetailsComponent implements OnInit {
@Output() sendMsgEventEmitter<string>=new EventEmitter<string>();
  constructor() {}
  ngOnInit() {}

  SendMessage() {
    this.sendMsg.emit('Message from Child');
  }
}

Parent Component html
<h2>Parent Component : {{msg}}</h2>
<app-details [companyName]="company" (sendMsg)="ReceivedMsg($event)"></app-details>

Parent Component 
import { ComponentOnInit } from '@angular/core';

@Component({
  selector: 'app-master',
  templateUrl: './master.component.html',
  styles: []
})
export class MasterComponent implements OnInit {
  msgstring;
  constructor() {}
  ngOnInit() {}
  ReceivedMsg(msgstring) {
    this.msg = msg;
    alert(msg);
  }
}

Q: What is the equivalent of ngShow and ngHide in Angular?
Just bind to the hidden property.
[hidden]="!myVar"

*ngIf vs [hidden]
*ngIf effectively removes its content from the DOM while [hidden] modifies the display property and only instructs the browser to not show the content but the DOM still contains it.

Continue Reading →

Sunday, 23 September 2018

Introduction To Design Pattern

Design patterns represent the best practices used by experienced object-oriented software developers. Design patterns are solutions to general problems that software developers faced during software development. 
Design pattern are evolved over a period of time by experienced software developers. They promote re usability which leads to a more robust and maintainable code. 
The Design patterns can be classified into three main categories: 
  1. Creational Patterns
  2. Structural Patterns
  3. Behavioral Patterns
Creational Patterns- Creational design patterns are related to the way of creating objects. Creational design patterns are used when a decision is made at the time of instantiation of a class.  
  • Factory method/Template
  • Singleton
  • Abstract Factory
  • Builder
  • Prototype
Structural Patterns- Structural design patterns are concerned with how classes and objects can be composed, to form larger structures.
 The structural design patterns simplifies the structure by identifying the relationships.
These patterns focus on, how the classes inherit from each other and how they are composed from other classes.
  • Adapter
  • Proxy
  • Bridge
  • Filter
  • Composite
  • Decorator
  • Façade
  • Flyweight
Behavioral Patterns- Behavioral patterns are concerned with the assignment of responsibilities between objects, or, encapsulating behavior in an object and delegating requests to it.
Unlike the Creational and Structural patterns, which deal with the instantiation process and the blueprint of objects and classes, the central idea here is to concentrate on the way objects are interconnected. In a word, we can say this: If Creational is about instantiation, and Structural is the blueprint, then Behavioral is the pattern of the relationship among objects.
  • Interpreter
  • Strategy pattern
  • Template method/ pattern
  • Chain of responsibility
  • Command pattern
  • Iterator pattern
  • Visitor pattern
What Is Factory Pattern?
Factory it's such a Design Pattern which defines an interface for creating an object, but lets the classes that implement the interface decide which class to instantiate. Factory Pattern lets a class postpone instantiation to sub-classes. For more info. clink on the link  http://softmindit.blogspot.com/Link 1

What is Singleton Pattern
Singleton pattern is a creational pattern which allows only one instance of a class to be created which will be available to the whole application. The major advantage of Singleton design pattern is its saves memory because the single instance is reused again and again; there is no need to create a new object at each request. For example, in our application, we can use a single database connection shared by multiple objects, instead of creating a database connection for every request.

What are the drawbacks of using singleton design pattern?
The major drawbacks of using singleton design pattern are:
a)Singleton causes code to be tightly coupled. The singleton object is exposed globally and is available to a whole application. Thus, classes using this object become tightly coupled; any change in the global object will impact all other classes using it.
b)Singleton Pattern does not support inheritance.

Adapter: is a structural design pattern This allows incompatible classes to work together by converting the interface of one class into another.  
 If you have two applications, with one spitting out output as XML with the other requiring JSON input, then you’ll need an adapter between the two to make them work seamlessly.

Proxy: is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object. Click here for more

What Is Strategy Pattern?
In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern.
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.
Real-World Analogy: Imagine that you have to get to the airport. You can catch a bus, order a cab, or get on your bicycle. These are your transportation strategies. You can pick one of the strategies depending on factors such as budget or time constraints. LINK 1Link 2

Intercepting Filter Pattern: The intercepting filter design pattern is used when we want to do some pre-processing / post-processing with request or response of the application. Filters are defined and applied on the request before passing the request to actual target application. Filters can do the authentication/ authorization/ logging or tracking of request and then pass the requests to corresponding handlers. Following are the entities of this type of design pattern.

Observer PatternThis pattern is a one-to-many dependency between objects so that when one object changes state, all its dependents are notified.
 For the sake of simplicity, think about what happens when you follow someone on Twitter. You are essentially asking Twitter to send you (the observer) tweet updates of the person (the subject) you followed. The pattern consists of two actors, the observer who is interested in the updates and the subject who generates the updates.
 A subject can have many observers and is a one to many relationship. However, an observer is free to subscribe to updates from other subjects too. You can subscribe to news feed from a Facebook page, which would be the subject and whenever the page has a new post, the subscriber would see the new post.


MVC Pattern: MVC Pattern stands for Model-View-Controller Pattern. This pattern is used to separate application's concerns.
For more design patter under the link Click here
Continue Reading →

Garbage Collection and Finalization Queue

Finalize is a special method that is automatically called by the garbage collector (GC) before the object is collected. This method is only called by the GC. The destructor in C# is automatically translated into Finalize. You can see the IL code using IDASM where you will see that destructor is renamed to finalize.

When a new object is created, the memory is allocated in the managed heap. If newly created object have a Finalize() method or a destructor then a pointer pointing to that object is put into the finalization queue. Basically, finalization queue is an internal data structure that is controlled and managed by the GC. Hence each pointer in finalization queue points to an object that have its Finalize method call before the memory is reclaimed.

Generations
The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0: This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation.

Generation 1: This generation serves as a buffer between short-lived objects and long-lived objects.

Generation 2: This generation holds long-lived objects like a static and global variable, that needs to be persisted for a certain amount of time. Objects which are not collected in generation Zero, are then moved to generation 1, such objects are known as survivors, similarly objects which are not collected in generation One, are then moved to generation 2 and from there onwards objects remain in the same generation.

Before the collections for dead objects, the garbage collector looks into the finalization queue for pointers identifies these objects. If the pointer found, then the pointer is flushed from the finalization queue and append to the freachable queue .The freachable queue is also an internal data structure and controlled by the garbage collector. Now each and every pointer with in the freachable queue will identify an object that is ready to have its Finalize method called.

Memory allocation
  • Garbage Collector (GC) is the part of the .NET framework that allocates and releases memory for your .NET applications.
  • When a new process is started, memory is allocated in to the managed heap.
  • Objects are allocated in the heap continuously one after another.
  • Memory allocation is a very fast process as it is just the adding of a value to a pointer.
Memory release
The garbage collector's optimizing engine determines the best time to perform a collection based on the allocations being made. When the garbage collector performs a collection, it releases the memory for objects that are no longer being used by the application. It determines which objects are no longer being used by examining the application's roots. An application's roots include static fields, local variables and parameters on a thread's stack, and CPU registers. Each root either refers to an object on the managed heap or is set to null. The garbage collector has access to the list of active roots that the just-in-time (JIT) compiler and the runtime maintain. Using this list, the garbage collector creates a graph that contains all the objects that are reachable from the roots. https://docs.microsoft.com

When GC Gets Triggered?
There are no specific timings for GC to get triggered, GC automatically starts operation on the following conditions:
  1. When virtual memory is running out of space.
  2. When allocated memory is suppressed acceptable threshold (when GC found if the survival rate (living objects) is high, then it increases the threshold allocation).
  3. When we call GC.Collect() method explicitly, as GC runs continuously, we actually do not need to call this method.
Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives