Wednesday, March 15, 2017

Difference between Deferred execution and Immediate execution in LINQ ?

Deferred Execution

In case of differed execution, a query is not executed at the point of its declaration. It is executed when the Query variable is iterated by using loop like as for, foreach.

Antother way of explain:

In LINQ, execution of a query is usually deferred until the moment when you actually request the data.

Example Code snippet:

  1. DataContext context = new DataContext();

  1. var query = from customer in context.Customers
  1. where customer.City == "Delhi"
  1. select customer; // Query does not execute her
  2.  
  1. foreach (var Customer in query) // Query executes here
  1. {
  1. Console.WriteLine(Customer.Name);
  1. }

A LINQ query expression often causes deferred execution. Deferred execution provides the facility of query reusability, since it always fetches the updated data from the data source which exists at the time of each execution.

Immediate Execution

In case of immediate execution, a query is executed at the point of its declaration. The query which returns a singleton value (a single value or a set of values) like Average, Sum, Count, List etc. caused Immediate Execution.
You can force a query to execute immediately of by calling ToList, ToArray methods.
  1. DataContext context = new DataContext();
  2. var query = (from customer in context.Customers
  3. where customer.City == "Delhi"
  4. select customer).Count(); // Query execute here
Immediate execution doesn't provide the facility of query re-usability since it always contains the same data which is fetched at the time of query declaration.


References:
http://www.dotnettricks.com/learn/linq/difference-between-deferred-execution-and-immediate-execution




No comments:

Post a Comment