sharmanilesh
sharmanilesh
Untitled
10 posts
Don't wanna be here? Send us removal request.
sharmanilesh · 2 years ago
Text
C# Delegates
Delegates can be compared with a function pointer in C/C++. It is an instance which can internally points to a memory location containing a method. As mentioned, it can reference to a method where the latter must match the signature for which a delegate is defined for. C# delegates provides the power of function pointers with the type safety of .Net.
We can have Single or Multicast delegates which sometimes also used as method chains. .Net itself provides us with some specific delegates like Func, Action and Predicate. Delegate are often used with the Events where the triggering of an event generally follows with the execution of lines of code.
Syntax:
[modifier] delegate [return_type] [delegate_name] ([parameter_list]);
Delegates provides us the following advantages:
It serves as an internal pointer to a method.
It can be used for Method chaining.
It can be used in places where we need Method chaining upon triggering of some events.
Delegates are created internally when Anonymous methods and Lambda expression gets combined internally.
They are very useful in scenarios related to callback functions.
Summarizing we can say that Delegates are powerful tools used to replicate the functionality of managed internal function pointer.
0 notes
sharmanilesh · 2 years ago
Text
Ubiquitous language in Programming
What?
When we say programming, it is actually a set of instructions which are written to instruct a dumb enough computer system to understand and execute what we are trying to imply. When Programming language first developed it is in the form of 0’s and 1’s and it is very hard to write the programs, gradually we moved on to writing some of the commands in the form of English letters. Finally came a phase where we try to eventually speak with the systems in the form of language which is near to what we speak but in a different manner.
Talking about Ubiquitous language it is a convention to write literals in a program in such a manner that it almost resembles the functionality it is going to perform/provide.
Why?
This came into limelight when we have more and more involvement of the Business-related entities into the technological domain, as with their advent it is getting more and more difficult to explain them what a piece of code is doing. It also helps others just by looking at the things.
How?
When we try to implement this in our system, we try to use the curated words related to specific things. Ex: a method trying to perform addition of integers can be written as “AddIntegers”.
This type of language can be self-explanatory among the team whether you are a Business-analyst, tester or developer, you can easily get hold of the things by reading it. It should be well accepted within the team and it is gradually evolved and enhanced over a period of time.
0 notes
sharmanilesh · 2 years ago
Text
.Net Retry Policy with Polly
Physical Networks are very volatile in nature hence they are prone to frequent disruptions, disruptions range from a simple Network failure to as complex as Throttling, but in any case, the requests get turned down and we get error at the Client end. We have existing methods to wait and retry for a number of times, but this has its own cons. The simple wait and retry does not provide enough resiliency, .Net required a resilient and robust mechanism to overcome this.
To overcome the above hurdles, we have Polly.Net it is a Wait and Retry mechanism but with some added spices in it e.g., Exponential Backoff.
Polly is a kind of circuit breaker, taking example or city roads if a car gets crashed in the existing road, we block the paths leading to it and wait until the things gets hygienic, a better example would be the home electrical system where when a fault is discovered the electrical circuit automatically breaks.
We have a number of options present in Polly where we can implement different techniques based on the scenarios, some of them are:
Basic Circuit breaker
Advance Circuit breaker
Wait and Retry
Exponential backoff
Fallback
Fallback and Retry
Timeout
Polly's Cache
Bulkhead Isolation
These policies when combined with proper implementation proves your application to be fault tolerant and resilient even with some complex failure situations.
References: https://www.pluralsight.com/blog/software-development/intro-to-polly
0 notes
sharmanilesh · 2 years ago
Text
C# HttpMessageHandler
In .Net environment the request and response pass through a series of handlers by default before it gets served and the response is returned to the client. These request interceptors which intercepts the request flow and divert it according to some predefined paths are termed as HttpMessageHandler in .Net.
Some of the classes which are responsible for the same are:
DelegatingHandler
HttpMessageHandler
HttpClientHandler
WebRequestHandler
These classes are being derived by HttpMessageHandler and are responsible to override the appropriate methods, they must make sure to write Thread safe code in this as it can be concurrently called by various clients (in the form of request).
They also provide us the vivid functionalities; each is defined in a separate way to cater to a specific kind of Task. For example, the HttpClientHandler class specifically deals with task like authentication and acting as proxies, whereas DelegatingHandler processes the HttpResponse message to other handlers.
Hence using the HttpMessageHandler we can Provide ourselves to tinker with the request and response pipelines in a flexible manner and perform some of the tedious tasks like authorization/authentication etc. before actually hitting the actual logical code to be processed.
References:https://learn.microsoft.com
0 notes
sharmanilesh · 2 years ago
Text
Locking in C#
C# Multithreading allows us to leverage shared spaces among various instances running same lines of code and sharing same memory location. This itself comes along with its retrospective effects, where its management is quite a headache for programmers.
To solve the management scenarios as mentioned, we use Locks. Locks are of various types and they themselves come along with their positives and negatives.
To understand the locking, we have to know what a Deadlock is, for the same consider a scenario where two kids wanted to play with the same toy and approach it together and starts fighting for the same, some important points related to this are
Since both are kids, we cannot console them after getting deadlocked for the toys as with the Threads we can’t.
Both will not be able to use that after the above scenario.
Wastage of resource (toy) as nobody is able to play.
Wastage of Parents time to console them, as the Processor time with Threads to resolve.
By looking at the above cases you must understood that we should avoid a deadlock and implement the various locking mechanism at our exposure from C#.
There are multiple things at our disposal such as Mutex, Lock objects waits etc. Hence in order to perform thing asynchronously and efficiently using Threads we always strive to avoid these condition and use optimum strategy as per our need.
0 notes
sharmanilesh · 2 years ago
Text
PLINQ
The Asynchronous counterpart of LINQ to object query is termed as PLINQ. While the LINQ typically get its behaviors and properties using System.Linq, the PLinq gets the corresponding from System.Linq.ParallelEnumerable.
When we deal with the parallel programming using the Task Parallel Library and queries the Objects generally it gets a bit slower using LINQ owing to the ultimate objective to perform the task efficiently and faster. The idea for the same gets a boost using PLINQ, here we have option to asynchronously query the objects and assign it to various Threads under execution.
How?
The ParallelEnumerable class exposes the functionality that is required to achieve the objective for such type of conditions.
Some of the methods that can be used are
AsParallel().
WithDegreeOfParallelism()
ForAll()
When?
PLINQ should be carefully used as it can make things complex and adds overburden to existing implementations, since its implementation requires first breaking the things then assigning it to various threads and ultimately merging them to obtain the final result.
We can keep in mind things like Ordering of Objects, final result whether it should be sorted or not etc. There are numerous helpers provided to us with the LINQ:
ForAll Operator
Cancellation Token
Custom Partitioners
Exception Handling using Aggregate Exception
Summarizing the overall concept, we can say that it is a powerful thing at the exposure but it should be used wisely to avoid complexities and unnecessary burden to the code.
References: https://learn.microsoft.com
0 notes
sharmanilesh · 2 years ago
Text
Task Parallel Library
C# Multithreading offers us quite unique resources to deal with some of the complex scenarios where efficiency is to be preserved along with the consistency, but it has its cons over the traditional approach.
TPL is introduced in .Net Framework 4, It can be imagined as wrapper present over the Multithreading which tries to manage the cumbersome threading environment. It is an exposed set of APIs and Public Types in “System.Threading” and “System.Threading.Tasks” namespaces. It handles everything related to Threads starting from its creation till its Termination. In short, we can say that TPL manages the parallelism which are offered by the Threads and at the same time provides us the flexibility.
While TPL provides us with a lot of benefits it does have its implications too, some of the scenarios are not well suited for the TPL it can lead to slow execution of the codes. We can avoid such scenarios where the code execution is imperatively sequential in nature, and introducing TPL can increase in execution complexity.
TPL execution depends on some of the mentioned scenarios as well, like
Computational cost of the overall work.
The number of logical cores on the system (degree of parallelism).
The number and kind of operations.
The type of merge options.
The kind of partitioning.
References: https://learn.microsoft.com
0 notes
sharmanilesh · 2 years ago
Text
C# Covariance and Contravariance
C# exhibits wide plethora of embedded processes (programming paradigms) to perform various tasks. Covariance and Contravariance are some of such processes. It helps implicit conversion amongst various reference type based on their hierarchy.
Covariance generally deals with the Type which is more derived in nature then the Type which is less derived, while Contravariance is opposite of it.
The working of Covariance can be seen in the C# class libraries as well, e.g., we assign string type to a list catered to serve Object Type, hence assigning a more derived Type to a less derived Type.
The working of Contravariance can be seen in the C# class libraries where we are assigning a less derived Type to a more derived Type.
These are created keeping in mind more complex mechanism where we are dealing with variant interfaces and delegates. C# also allows us to create the same.
0 notes
sharmanilesh · 2 years ago
Text
Decoding C# Reference Types
To understand this, we will try What, Why, When & How.
What?
C# reference types are basically variables that stores the references to some memory location, these memory locations are often Objects. In naive language you can consider a reference type just like a locker and key combination, where locker can only be accessed when you have its key, while key itself does not have any significance but you cannot access a locker without it.
In same manner objects can be accessed with the use of reference types.
Why?
As the Primitive types have local scope hence Stack are used to store them. When the stack frames are destructed upon subsequent method calling the primitive types follow the same fate, but when we talk about memory pointed out by reference types, we need them to live longer and can be reference outside of their scope as well, hence they get their place in Heap and is the reason for their existence.
When?
While taking example of C# we are not in control of when we need what? It is automatically decided by the CLR when a type is internally defined as Reference types and starts pointing to a Heap location.
We can however judge by their Type and assume where it is going to get allocated.
How?
Using the Memory Management Techniques, the C# compiler and its Runtime basically allocates and deallocates the memory related to the same. We can however leverage the flexibility that is provided by the same.
It’s based on the scenarios which depends on the scope and lifetime of the variables, the same variables can be declared accordingly in our programs.
In a nutshell we can say that these Reference types are tools, which are further used by various other Techniques for efficient and enhanced Memory Management.
1 note · View note
sharmanilesh · 2 years ago
Text
C# Garbage Collection
To understand this, we will try What, Why, When & How.
What?
Garbage Collection is a technical word for Memory Management used by Microsoft in C#.
There are basically three Generation of Garbage collection:
Gen 0
Gen 1
Gen 2
The First generation is often designated for the objects that are short lived, while the other two generations are often used for the objects that has longer lifetime.
Why?
We are physically limited with the amount of space that is present inside a system and hence to use it efficiently we need its proper management.
When?
In basic terminology we can compare Garbage Collection with a person cleaning restaurant table using below points,
Whenever a person is using it, it is not generally cleaned until there is no space to put food then the table is cleaned for the dishes in which the food is already finished.
When a person finishes his meal and leaves the Restaurant then the Table(space) can be provided to another one.
A customer arriving always gets a clean table.
A Customer can only use his table and can’t share food from another table as long as they don’t belong to them.
Using the above pointers, we can summarize in a generalized way that:
Entities in C# are Garbage collected from memory if they are out of scope.
Entities are always provided space which are written in a fresh manner by them.
Memory spaces related to particular programs are confined and does not allow any other programs to access its memory space.
How?
Each Program basically has a separate Memory Segment which is allocated using VirtualAlloc and deallocated using VirtualFree Windows functions, Deallocation or compaction process gets triggered on need basis.
Firstly, the objects are checked across Gen0, the object who does not have any references pointing currently gets deallocated and remaining objects are moved to Gen1, this process gets repeated and compaction generally does not occur in Gen1/Gen2 until the space is there in Gen0 heap.
Summarizing everything in a nutshell, basically Garbage collection is a Memory Management Technique using various algorithm, it optimizes the memory usage and negates any memory leaks.
5 notes · View notes