affiliate_link

Tuesday, March 13, 2018

Multithreading locking different ways?


The lock statement is analogous to Monitor.Enter, which does potentially block. Granted, in your example code, there shouldn't be any blocking issues; but I would wager that since lock provides blocking, it does a little more work (potentially) than TryEnter does.

1. Lock
2. Monitor.Enter
3. Monitor.TryEnter

100 iterations:
lock: 4.4 microseconds
Monitor.TryEnter: 16.1 microseconds
Monitor.Enter: 3.9 microseconds
100000 iterations:
lock: 2872.5 microseconds
Monitor.TryEnter: 5226.6 microseconds
Monitor.Enter: 2432.9 microseconds
This seriously undermines my initial guess and shows that, on my system, lock (which performs about the same as Monitor.Enter) actually drastically outperforms Monitor.TryEnter.

Monday, March 12, 2018

Difference between WCF and Web API?

The .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use.

Web Service

  • It is based on SOAP and return data in XML form.
  • It support only HTTP protocol.
  • It is not open source but can be consumed by any client that understands xml.
  • It can be hosted only on IIS.

WCF

  • It is also based on SOAP and return data in XML form.
  • It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  • The main issue with WCF is, its tedious and extensive configuration.
  • It is not open source but can be consumed by any client that understands xml.
  • It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  • To use WCF as WCF Rest service you have to enable webHttpBindings.
  • It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  • To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  • Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified.
  • It support XML, JSON and ATOM data format.

Web API

  • This is the new framework for building HTTP services with easy and simple way.
  • Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  • Unlike WCF Rest service, it use the full feature of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  • It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  • It can be hosted with in the application or on IIS.
  • It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  • Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API

  • Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  • Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  • Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  • Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

What is Action Delegate?

Microsoft introduced some pre-built delegates so that we don't have to declare delegates every time. Action is one of the pre-built delegates.

Action in C# represents a delegate that has void return type and optional parameters. There are two variants of Action delegate.
  1. Action
  2. Action<in T>

Non-Generic Action Delegate

First variant is non-generic delegate that takes no parameters and has void return type. In this Action delegate, we can store only those methods which has no parameters and void return type.
 








static void Main(string[] args)
{
    Action doWorkAction = new Action(DoWork);
    doWorkAction(); //Print "Hi, I am doing work."
}
 
public static void DoWork()
{
    Console.WriteLine("Hi, I am doing work.");
}
 
We can also store method in the Action delegate with direct initializing with the method. Below is the example.










static void Main(string[] args)
{
    Action doWorkAction = DoWork;
    doWorkAction(); //Print "Hi, I am doing work."
}
 
public static void DoWork()
{
    Console.WriteLine("Hi, I am doing work.");
}

Generic Action Delegate

We can also store method in the Action delegate with direct initializing with the method.

We have to choose Action delegate according to the method, which we want to store. If our method takes two parameters, then we have to choose action delegate which has two parameters Action<in T1, T2>(T1 arg1, T2 arg2). Below are some examples


static void Main(string[] args)
{
    Action<int> firstAction = DoWorkWithOneParameter;
    Action<int, int> secondAction = DoWorkWithTwoParameters;
    Action<int, int, int> thirdAction = DoWorkWithThreeParameters;
 
    firstAction(1); // Print 1
    secondAction(1, 2); // Print 1-2
    thirdAction(1, 2, 3); //Print 1-2-3
}
 
public static void DoWorkWithOneParameter(int arg)
{
    Console.WriteLine(arg);
}
 
public static void DoWorkWithTwoParameters(int arg1, int arg2)
{
    Console.WriteLine(arg1 + "-" + arg2);
}
 
public static void DoWorkWithThreeParameters(int arg1, int arg2, int arg3)
{
    Console.WriteLine(arg1 + "-" + arg2 + "-" + arg3);
}

Action with Lambda Expression

We can use Lambda expression with Action delegate. Below is the example.





















static void Main(string[] args)
{
    Action act = () =>
    {
        Console.WriteLine("No Parameter");
    };
 
    Action<int> actWithOneParameter = (arg1) =>
        {
            Console.WriteLine("Par: " + arg1);
        };
 
    Action<int, int> actWithTwoParameter = (arg1, arg2) =>
        {
            Console.WriteLine("Par1: " + arg1 + ", Par2: " + arg2);
        };
 
    act();
    actWithOneParameter(1);
    actWithTwoParameter(1, 2);
}

Wednesday, December 27, 2017

Func vs. Action vs. Predicate?

In C#, Action and Func are extremely useful tools for reducing duplication in code and decreasing coupling.

A simple way of thinking about Action<>

Most of us are pretty familiar with finding sections of repeated code, pulling that code out into a method and making that method take parameters to represent the differences.
public void SteamGreenBeans()
{
    var greenBeans = new GreenBeans();
    Clean(greenBeans);
    Steam(greenBeans, Minutes.Is(10));
    Serve(greenBeans);
}
 
public void SteamCorn()
{
    var corn = new Corn();
    Clean(corn);
    Steam(corn, Minutes.Is(15));
    Serve(corn);
}
 
public void SteamSpinach()
{
    var spinach = new Spinach();
    Clean(spinach);
    SteamVegetable(spinach, Minutes.Is(8));
    Serve(spinach);
}
 
Each one of these methods pretty much does the same thing.  The only difference here is the type of vegetable and the time to steam it.
It is a simple and common refactor to refactor that code to:
public void SteamGreenBeans()
{
   SteamVegetable(new GreenBeans(), 10);
}
 
public void SteamCorn()
{
    SteamVegetable(new Corn(), 15);
}
 
public void SteamSpinach()
{
    SteamVegetable(new Spinach(), 8);
}
 
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Steam(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
Much better, now we aren’t repeating the “actions” in 3 different methods.
Now let's imagine we want to do something more than steam.  We need to be able to fry or bake the vegetables.  How can we do that?
Probably we will have to add some new methods for doing that.  So we will end up with something like this:
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Steam(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
 
public void FryVegetable(Vegetable vegetable, int timeInMinutes)
{
    Clean(vegetable);
    Fry(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
 
public void BakeVegetable(Vegetable vegetable, int timeInMinutes)
{
   Clean(vegetable);
   Bake(vegetable, Minutes.Is(timeInMinutes));
   Serve(vegetable);
}
Hmm, lots of duplication again.  No problem.  Let's just do what we did to the first set of methods and make a CookVegetable method.  Since we always clean, then cook, then serve, we should be able to just pass in the method of cooking we will use.
Oh wait, how do we do that?  We can’t just extract out Bake  or Fry  or Steam, because the Bake, Fry and Steam methods are logic and not data.
Unless… unless we can make them data.  Can we do that?
We sure can, check this out:
public void SteamVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Steam, timeInMinutes);
}
 
public void FryVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Fry, timeInMinutes);
}
 
public void BakeVegetable(Vegetable vegetable, int timeInMinutes)
{
    CookVegetable(vegetable, Bake, timeInMinutes);
}
 
public void CookVegetable(Vegetable vegetable,
   Action<Vegetable, int> cookingAction,
   int timeInMinutes)
{
    Clean(vegetable);
    cookingAction(vegetable, Minutes.Is(timeInMinutes));
    Serve(vegetable);
}
 
We got rid of the duplicated code the same way we did when we did our first refactor, except this time we parameterized method calls instead of data.
If you understood this, you understand Action.  Action is just a way of treating methods like they are data. Now you can extract all of the common logic into a method and pass in data that changes as well as actions that change.
Congratulations, you are doing the strategy pattern without having to create an abstract base class and a huge inheritance tree!
So when you see Action, just think “ah, that means I am passing a method as data.”
It really is as simple as that.
Action<Vegetable, CookingTime> translated to English is: “A method that takes a Vegetable and a CookingTime as parameters and returns void.”

What about Func<>?

If you understand Action, you understand Func.
Func<X, Y, Z> translated to English is: “A method that takes an X, and a Y as parameters and returns a Z”.”
The only difference between Action and Func is that Func’s last template parameter is the return type.  Funcs have non-void return values.
Bonus: Predicate is a Func that always returns a boolean.
That’s all there is to it.  There really isn’t a need to know much more than that to make sure of Action and Func in order to start using them.


Wednesday, December 20, 2017

Association vs Aggregation vs Composition

The question "What is the difference between association, aggregation and composition" has been frequently asked lately. Actually, Aggregation and Composition are subsets of association meaning they are specific cases of association. In both aggregation and composition object of one class "owns" object of another class. But there is a subtle difference:
  • Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.
  • Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.

Monday, December 18, 2017

Dispose vs Finalize?

The finalizer is for implicit cleanup - you should use this whenever a class manages resources that absolutely must be cleaned up as otherwise you would leak handles / memory etc...
Correctly implementing a finalizer is notoriously difficult and should be avoided wherever possible - the SafeHandle class (avaialble in .Net v2.0 and above) now means that you very rarely (if ever) need to implement a finalizer any more.
The IDisposable interface is for explicit cleanup and is much more commonly used - you should use this to allow users to explicitly release or cleanup resources whenever they have finished using an object.
Note that if you have a finalizer then you should also implement the IDisposable interface to allow users to explicitly release those resources sooner than they would be if the object was garbage collected.
See DG Update: Dispose, Finalization, and Resource Management for what I consider to be the best and most complete set of recommendations on finalizers and IDisposable.

How do I know if a class in C# is unmanaged, whether I have to implement the IDisposable interface?

StreamReader is not an unmanaged resource itself, but it wraps one, and therefore it implements IDisposable. Anything that implements IDisposable should be disposed. Other than that, you don't have to worry about unmanaged resources unless you're using Windows API calls via PInvoke (because anything that wraps resources allocated that way should implement IDisposable)

using (StreamReader sr = new StreamReader(filename)) {
     txt = sr.ReadToEnd();
}