Important Facts of Asynchronous Programming in .NET

Modern apps make extensive use of file and networking I/O. I/O APIs traditionally block by default, resulting in poor user experiences and hardware utilization unless you want to learn and use challenging patterns.

Task-based async APIs and the language-level asynchronous programming model invert this model, making async execution the default with few new concepts to learn.

Async code has the following characteristics:

  • Handles more server requests by yielding threads to handle more requests while waiting for I/O requests to return.
  • Enables UIs to be more responsive by yielding threads to UI interaction while waiting for I/O requests and by transitioning long-running work to other CPU cores.
  • Many of the newer .NET APIs are asynchronous.
  • It’s easy to write async code in .NET

One of the main advantages of using asynchronous methods is with I/O-based code.

By doing an await, you can let a thread be reused to do other work while the I/O is in flight.

The biggest misunderstanding about Asynchronous programming in many developers is asynchronous method automatically spawns a new thread, and that is not the case.

Recent improvements Microsoft has made towards Asynchronous programming is “Generalized Async Return Types

This means that you’re no longer limited to using Task or Task<T> as the return type for an asynchronous method. As long as the return type satisfies the asynchronous pattern, you’re good. Using this new ValueTask, you can avoid memory allocations, which can help in addressing performance issues.

Top Nuget Packages that Microsoft recommend for asynchronous programming are “System.Collections.Concurrent” and “System.Collections.Immutable“.

System.Collections.Immutable provides collections that allow a developer to use a collection (e.g. ConcurrentBag or ConcurrentDictionary) in a concurrent fashion safely. Therefore, the developer doesn’t need to do their own locking mechanisms to use the collection. Immutable collections allow developers to share collections safely because updates are only seen by the code that made the update.

Avoid void as a return type for asynchronous methods at all costs.

The only time it’s valid to do this is with an event handler. Otherwise, asynchronous methods should always return a Task type.

Immutable structures are very important when working with concurrent programming.

The main advantage with immutable data types is that you can share them across multiple tasks without worrying about synchronizing their contents. By their definition, they’re immutable, so if a task decides to “change” an immutable object, it will get a new version of that object. If another task has a reference to the original immutable object, it doesn’t change.

Take advantage of C# features to write immutable structures.

This means defining fields with the readonly keyword and properties that only have getters (not even private setters). Also, C# now allows you to specify a method parameter with the in keyword, which means that reference cannot be changed.

That’s all for now. I hope these facts will help you while doing Asynchronous Programming for your projects 🙂

Immutable objects in C#

In this article Shivprasad koirala explain about Immutable in C#.

It covers following points:

1. Introduction
2. What are immutable objects?
3. Where are immutable objects used?
4. How can we create immutable objects in C#?

Read Full Article: Click here.

Jay Ganesh !!!!!

OOPS – Polymorphism and Inheritance (Dynamic Binding/Run Time Polymorphism)

This Article summarizes the following points written by Akhil Mittal :

  • In C#, We can equate an object of a base class to a derived class but not vice versa.
  • The override modifier is needed as the derived class methods will get first priority and be called upon.
  • These modifiers like new and override can only be used if the method in the base class is a virtual method. Virtual means that the base class is granting us permission to invoke the method from the derived class and not the base class. But, we have to add the modifier override if our derived class method has to be called.
  • If the base class object declared the method virtual and the derived class used the modifier override, the derived class method will get called. Otherwise, the base class method will get executed. Therefore for virtual methods, the data type created is decided at run time only.
  • All the methods not marked with virtual are non virtual, and the method to be called is decided at compile time, depending upon the static data type of the object.
  • An override method is a method that has the override modifier included on it. This introduces a new implementation of a method. We can’t use the modifiers such as new, static or virtual along with override. But abstract is permitted.

Read full article –

Hope this will help !!!

Jay Ganesh

All About C# Access Modifiers

Access modifiers (or access specifiers) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components.

Summary of the article:

1) The default access modifier is private for class members.
2) A class marked as internal can have its access limited to the current assembly only.
3) Namespaces as we see by default can have no accessibility specifiers at all. They are by default public and we cannot add any other access modifier including public again too.
4) A class can only be public or internal. It cannot be marked as protected or private. The default is internal for the class.
5) Members of a class can be marked with all the access modifiers, and the default access modifier is private.
6) Protected internal means that the derived class and the class within the same source code file can have access.
7) Between public and internal, public always allows greater access to its members.
8) Base class always allows more accessibility than the derived class.
9) The return values of a method must have greater accessibility than that of the method itself.
10) A class marked sealed can’t act as a base class to any other class.
11) Since we cannot derive from sealed classes, the code from the sealed classes cannot be overridden.
12) We need to initialize the const variable at the time we create it. We are not allowed to initialize it later in our code or program.
13) Like classes, const variables cannot be circular, i.e., they cannot depend on each other.
14) A const field of a reference type other than string can only be initialized with null.
15) One can only initialize a const variable to a compile time value, i.e., a value available to the compiler while it is executing.
16) A constant by default is static and we can’t use the instance reference, i.e., a name to reference a const. A const has to be static as no one will be allowed to make any changes to a const variable.
17) A const variable cannot be marked as static.
18) A variable in C# can never have an uninitialized value.
19) Static variables are always initialized when the class is loaded first. An int is given a default value of zero and a bool is given a default of False.
20) An instance variable is always initialized at the time of creation of its instance.
21) A static readonly field cannot be assigned to (except in a static constructor or a variable initializer).

Rad full article

Jay Ganesh

Bind enum to ddl

Sometime we need to bind the value and the name of the enum to the dropdownlist. here is the code that will help us to achieve this.

here I have created a method to convert enum into hashtable :

    public Hashtable ConvertEnumToHashTable(Type myenum)
        string[] names = Enum.GetNames(myenum);
        Array values = Enum.GetValues(myenum);
        Hashtable ht = new Hashtable();
        for (int i = 0; i < names.Length; i++)
            ht.Add(Convert.ToInt32(values.GetValue(i)).ToString(), names[i]);
        return ht;

Now here is code that shows you how to use this function :

    protected void Page_Load(object sender, EventArgs e)
        Hashtable ht = ConvertEnumToHashTable(typeof(myenum));
        myDDL.DataSource = ht;
        myDDL.DataTextField = "value";
        myDDL.DataValueField = "key";



Hope this code will help !!!

Jay Ganesh