Microsoft Build 2021 Highlights

As shared in my earlier post, recently Microsoft held its Build Conference 2021 as a virtual event. It spanned across for more than two days that touched upon various topics. It was not as big as it used to be in person for last several years. There were numerous updates that they shared which I have tried to cover here.

msbuild-highlights

To empower developers, to empower you, to empower the world.

Microsoft vision

Core Themes

Microsoft unveiled a handful of news and tools to empower developers. There were multiple Innovative AI, mixed reality solutions, intelligent cloud tools solutions shared. Core themes for the conference were as depicted below:

build-theme

With so much changing in working mode, Microsoft shared how they are looking to support for Operational excellence with their developer platform. A deep dive session on how to increase developer velocity with Microsoft’s end to end platform was shared during the conference.

Further, data being the key for future transformations, they showcased how Azure Data was being built as a platform that could support AI & data governance.

ms-data-ai
dev-toolchain
ms-ai

They now support building deeper Artificial Intelligence infrastructure for everyone. This would help in easy onboard and usage of Azure services to have more proactive approach to solutions. Details about how to harness the power of data in our applications with Azure can be viewed here.

With Microsoft vision to empower developers, there was a session on how to build cloud native solutions that can run on premise, on edge and on multiple cloud. Recording of the session can be seen here.

ms-cloud-native

Covid has probably made the biggest shift in how we work today. A hybrid future work style is being imagined with new operating models to work, learn or collaborate.

Microsoft Teams is one of the Microsofts fastest growing product with 145 million daily active users to date.

With new working style, transformation seems to be an opportunity where cross device collaboration would be the key. Microsoft surely knows the same and are investing in it. Following session shares on how they are progressing on the collaborative applications journey: Build the next generation of collaborative apps for hybrid work

ms-collaborative-app

Based on the different kind of services, need of support, scalability options and various other factors puts software as a service, a much needed way. Microsoft looked focused on the same and shared on how they are working towards a cloud native SaaS apps composed on top of other clouds and components.

Microsoft also held a session showcasing how they are working towards helping build Metaverse Apps (digital and physical mixing up) incorporating digital twins, IOT, Autonomous systems, Power platforms and Mesh.

digital-twins
autonomous-systems
ms-mesh

Announcements

Like always, there were few key announcements about new initiatives and solutions as mentioned below:

ms-announcements

Real World

Through sessions, Microsoft covered few examples on how various other organizations are leveraging Microsoft solutions to provide awesome customer experience with speed and accuracy.

ms-toyota
Fusion Teams for mission critical delivery app
ms-twitter
Generate captions for live audio conversations using MS Speech service
ms-walmart
Power eCommerce transactions using MS CosmosDB
ms-servicenow
Incident response using MS Teams, Graph & Bot
ms-finastra
Application development using MS Financial Services cloud, Teams & Azure
ms-abinbev
Track bottles till distribution processes using Metaverse stack

Nadella in his keynote also shared that because of Covid, digital transformations have accelerated and has advanced by 10 years.

ms-tech-intensity
ms-gdp10
ms-dev-growth
ms-github-growth

Post pandemic, virtual world will still have a significant role in the new normal. Solutions across industries would want to be connected and continue use the benefits of digital first responders. This would further fuel the innovations and development across technology.

Windows Update

Microsoft’s Build 2021 event didn’t had much of Windows-specific news. Few that came out were:

  • 21H1 windows update was rolled out with multiple security fixes
  • Support for Linux GUI apps on Windows 10 will come later this year
  • Continues promoting ARM – Qualcomm ARM/Snapdragon Developer Kit was announced
  • Fall update (aka Sun-Valley Update) might have renewed UX

Windows10 used by 1.3 billion – work, learn, connect and play

Microsoft

.NET Update

.NET 6 is the next version of .NET, a modern, open-source development platform for building apps for any OS with the best performance and productivity.

.NET 6 completes the unification of the platform and adds new capabilities for building web, native and hybrid apps for Linux, Windows, Mac, iOS and Android with a single codebase. Details can be viewed here: .NET 6 deep dive – what’s new and what’s coming

  • .NET 6 preview 4 available, .NET 6 planned to be released during .NET Conf 2021
  • Visual Studio 2022 under works, preview to be available soon

Imagine Cup 2021

imagine-cup

Make an impact through coding, collaboration, and competition. Innovate with passion to tackle global issues and bring your idea to life in the Imagine Cup.

Imagine Cup

One Winner out of four student teams from across the world was announced. Teams brought their innovations focused on four social good categories – Earth, Education, Healthcare, and Lifestyle. With intention to solve issues in their local and global communities, multiple teams participated and final four were selected after evaluation on various parameters.

Team REWEBA from Kenya were announced as the Imagine Cup 2021 World Champions.

What’s next

Learn, connect, and explore all of the sessions and on-demand content from Microsoft Build anytime, anywhere.

Microsoft

With virtual as normal, Microsoft hinted at having multiple What’s next virtual events to share updates through out the year. For now, they have asked to save the date June 24 as event to share all about the operating system’s updates.

All the MS Build sessions are recorded and can be viewed from here.

Reference: https://mybuild.microsoft.com/home

Sandeep Mewara Github
News Update
Tech Explore
Data Explore
samples GitHub Profile Readme
Learn Machine Learning with Examples
Machine Learning workflow
What is Data Science
Word Ladder solution
What is Dynamic Programming
Learn Microsoft Tech via Videos LiveTV Streams

Microsoft .NET 5 – all you need to know

As announced earlier, Microsoft released .NET 5 on Nov. 10 during .NET Conf 2020. It’s a major release with many new features and improvements to .NET Core 3. Keeping cross platform support and open source development as key base, going forward it kind of merges off .NET Framework and .NET Core.

dotnet-header

Plan

Microsoft started it’s journey of cross platform and open source in 2015. .NET 5 is a major milestone of this transition as .NET Framework 4.8 was the last major version of .NET Framework. Microsoft published a blog to explain how .NET 5 relates to .NET Framework.

.NET 5.0 is the main implementation of .NET going forward and .NET Framework 4.x is still supported.

dotnet-schedule
Source: Microsoft
dotnet-unified
Source: Microsoft

.NET 5 has been called as .NET Core vNext for quite some time now. It has following key principles:

– Produce a single .NET runtime and framework that can be used everywhere and that has uniform runtime behaviors and developer experiences.

– Expand the capabilities of .NET by taking the best of .NET Core, .NET Framework, Xamarin and Mono.

– Build that product out of a single code-base that developers (Microsoft and the community) can work on and expand together and that improves all scenarios.

Microsoft

Highlights

There are many improvements in .NET 5 like:

  • Performance across many components
  • Performance in .NET Libraries
  • Language C# 9 & F# 5
  • Application deployment options
  • Platform scope (includes Windows Arm64 & WebAssembly)

Details about these enhancements are here.

dot.net and Bing.com are already running on .NET 5 for months now

References

IDE

You need Visual Studio 16.8 or later to use .NET 5.0 on Windows and the latest version of Visual Studio for Mac on macOS. Latest C# extension for Visual Studio Code already supports .NET 5.0 and C# 9.

Impacts

There are few breaking changes with upgrade to .NET 5:

  • while migrating from version 3.1 of .NET Core, ASP.NET Core, or EF Core to version 5.0 of .NET, ASP.NET Core, or EF Core are captured here.
  • in Roslyn in C# 9.0 introduced with .NET 5 are captured here.
  • for migration from .NET Framework to .NET Core are captured here.
  • obsolete features in .NET 5 are captured here.

Deprecated

.NET 5 does not have few of the known technologies:

  • ASP.NET WebForms – Microsoft’s recommendation is to move to Blazor
  • Windows Communication Foundation (WCF) – Microsoft’s recommendation is to use gRPC
  • Windows Workflow Foundation (WWF) – recommendation is to look at CoreWF, a form of WF runtime

Advantages

.NET 5 helps if you have cross-platform needs or targeting microservices or want to use Docker containers. Based on how it is setup underlying, it helps in designing high-performance and scalable systems.

.NET 5 supports side-by-side installation of different versions of the .NET 5 runtime on the same machine. This allows multiple services or applications on the same server running on their own version of .NET 5 variant.

A detailed analysis and shareout can be read here.

Wrap Up

.NET 5 is a major step of the .NET journey planned ahead. Next would be .NET 6 next year (late in 2021), which will also be a long term (multi year) supported (LTS) version.

Microsoft is working towards a defined vision – same .NET API and languages working across operating system, application types and architectures.

With active support to previous .NET versions, we have time to assess, plan and adapt the new path.


Keep exploring!

Sandeep Mewara Github
News Update
Tech Explore
Data Explore
samples GitHub Profile Readme
Learn Machine Learning with Examples
Machine Learning workflow
What is Data Science
Word Ladder solution
What is Dynamic Programming
Learn Microsoft Tech via Videos LiveTV Streams Microsoft .NET5

Learn Microsoft Tech via Videos & Live Streams

Recently, Microsoft has invested and made extra efforts into putting up the resources to learn.

microsoft-learn

Recordings …

This September, Microsoft launched Video Hub, a new resource home for Tech Community Videos and Interactive Guides to help learn everything about major Microsoft products.

Access: Microsoft Tech Community Video Hub

Live …

Yesterday (Mid October), Microsoft launched .NET Live TV, a one stop shop for all .NET and Visual Studio Live Streams across Twitch and YouTube.

To view, visit: .NET Live TV

Sometime back, Microsoft launched Learn TV. It is a place to find the latest digital content to be updated on the latest announcements, features, and products from Microsoft.

To view, visit: Learn TV

Discover your path …

As shared on the Microsoft’s Learning site, irrespective of which stage you are in your carrier – a fresher or an experience professional, material can help learn hands on and gain confidence faster.

You can choose topics, learn at your own schedule and even do Microsoft based certifications. It even has suggestions and ratings for popular topics to guide further.

Explore: Microsoft Learn

Well, seems knowledge is all there and pretty organized for the taking.


Keep learning!

samples GitHub Profile Readme
Learn Python – Beginners step by step – Basics and Examples
Sandeep Mewara Github
Sandeep Mewara Learn By Insight
Matplotlib plot samples
Sandeep Mewara Github Repositories

Microsoft .NET Conference 2020

.NET Conf 2020 is a free virtual developer event organized by the .NET Community and Microsoft. I came across discussion if I am interested in speaking at the event as the call for content is now open.

The conference showcases the .NET platform for developers focusing on desktop, mobile, web, IoT, games, cloud and open source projects. Read details about the event here: .NET Conf 2020

If you feel interested, you don’t need to register for it. Just keep track of the dates and attend event session live here.

dotnet-conf-2020

This year .NET 5.0 will launch at .NET Conf 2020! Come celebrate and learn about the new release. We’re also celebrating our 10th anniversary and we’re working on a few more surprises.

Event highlight shared by .NET foundation


There would be live sessions by speakers from the community and .NET team members. One can ask questions live on Twitter, join the fun on Twitch and attend the virtual attendee parties. It would help know whats happening and upcoming in the .NET world.

Happy connecting!

LearnByInsight
Samples GitHub Profile Readme
Sandeep Mewara GithubIO

Read from console in VS Code

I moved to Apple Mac late last year because of different set of technologies now I work in. As shared in one of my previous posts, I use Visual Studio Code for programming in Python exploring Machine Learning. Though, for anything in .NET, I switch to a Windows VM and use Visual Studio.

For quick console apps, it feels painful to switch to a VM and work. Thus, I looked and installed C# extension in VS Code to try of. Details are here.

While running a console app, I got stuck to read any value from Console. In debug mode, IDE would stop on the Console.ReadLine() but whatever I type in Console would not go through.

I looked around and found that there are few settings for Console in VS Code. The console setting controls what console (terminal) window the target app is launched into.

"internalConsole" (default) : This does NOT work for applications that want to read from the console (ex: Console.ReadLine).

How to Solve it?

Suggested way to take input is to set the console setting as integratedTerminal. This is a configuration setting in the launch.json file under .vscode folder.

"integratedTerminal" : the target process will run inside VS Code’s integrated terminal (Terminal tab in the tab group beneath the editor). Alternatively add "internalConsoleOptions": "neverOpen" to make it so that the default foreground tab is the terminal tab.

Change the default setting like below:

vscode-read-console

With above change, the input and output will happen through integrated terminal like:

vscode-read-console-2

So far, it looks good and seems I will stick to Visual Studio Code on Mac for quick console applications.

Reference here.


Keep learning!

LearnByInsight
GitHub Profile Readme Samples

New C# features I really liked!

There has been many new features added to C# over last few years. A recent survey in CodeProject community lead me to the thought of sharing what I find really helpful. It spreads from C# 6.0 to C# 8.0. Below few made writing code easy, more fun and have improved productivity.

Null Conditional Operator (?. & ?[])

They make null checks much easier and fluid. Add a ? just before the the member access . or indexer access [] that can be null. It short-circuits and returns null for assignment.

// safegaurd against NullReferenceException

Earlier
if(address != null)
{
   var street = address.StreetName;
}
Now
var street = address?.StreetName;

// safegaurd against IndexOutOfRangeException

Earlier
if(row != null && row[0] != null)
{
   int data = row[0].SomeCount;
}
Now
int? data = row?[0]?.SomeCount;

Null Coalescing Operator (?? & ??=)

Null-coalescing operator ?? helps to assign default value if the properties is null. Often, used along with null conditional operator.

Earlier
if(address == null)
{
   var street = "NA";
}
Now
var street = address?.StreetName ?? "NA"; 

Null-coalescing assignment operator ??= helps to assign the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null.

The left-hand operand of the ??= operator must be a variable, a property, or an indexer element

Earlier
int? i = null;

if(i == null)
   i = 0;

Console.WriteLine(i);  // output: 0
Now
int? i = null;

i ??= 0;
Console.WriteLine(i);  // output: 0

String Interpolation ($)

It enables to embed expressions in a string. With a special character $ to identify a string literal as an interpolated string. Interpolation expressions are replaced by the string representations of the expression results in the result string.

Earlier
string address = string.Format("{0},{1}", HouseNo, StreetName);

log.Write("Address: "+ HouseNo.ToLower() + "," + StreetName);
Now
string address = $"{HouseNo}, {StreetName}";

log.Write($"Address: {HouseNo.ToLower()}, {StreetName}");

Auto-Property Initializer

It helps declare the initial value for a property as part of the property declaration itself.

Earlier
Language _currentLanguage = Language.English;
public Language CurrentLanguage
{
   get { return _currentLanguage; }
   set { _currentLanguage = value; }
}   

// OR

// Improvement in C# 3.0
public Language CurrentLanguage { get; set; }

public MyClass()
{
    CurrentLanguage = Language.English;
}
Now
public Language CurrentLanguage { get; set; } = Language.English;

using static

It helps to import the enum or static methods of a single class.

Earlier
public class Enums
{
    public enum Language
    {
        English,
        Hindi,
        Spanish
    }
}

// Another file
public class MyClass
{
    public Enums.Language CurrentLanguage { get; set; };
}
Now
public class Enums
{
    public enum Language
    {
        English,
        Hindi,
        Spanish
    }
}

// Another file
using static mynamespace.Enums

public class MyClass
{
    public Language CurrentLanguage { get; set; };
}

Tuples

They are lightweight data structures that contain multiple fields to represent the data members.

# Initialize Way 1
(string First, string Second) ranks = ("1", "2");
Console.WriteLine($"{ranks.First}, {ranks.Second}");

# Initialize Way 2
var ranks = (First: "1", Second: "2");
Console.WriteLine($"{ranks.First}, {ranks.Second}");

It support == and !=

Expression bodied get/set accessors

With it, members can be implemented as expressions.

Earlier
public string Title
{
    get { return _title; }
    set 
    { 
       this._title = value ?? "Default - Hello";
    }
}
Now
public string Title
{
    get => _title;
    set => this._title = value ?? "Default - Hello";
}

Access modifier: private protected

A new compound access modifier: private protected to indicate a member accessible by containing class or by derived classes that are declared in the same assembly. One more level of abstraction compared to protected internal.

// Assembly1.cs
public class BaseClass
{
    private protected int myValue = 0;
}

public class DerivedClass1 : BaseClass
{
    void Access()
    {
        var baseObject = new BaseClass();

        // Error CS1540, because myValue can only be
        // accessed by classes derived from BaseClass
        // baseObject.myValue = 5;

        // OK, accessed through the current 
        // derived class instance
        myValue = 5;
    }
}

//
// Assembly2.cs
// Compile with: /reference:Assembly1.dll
class DerivedClass2 : BaseClass
{
    void Access()
    {
        // Error CS0122, because myValue can only
        // be accessed by types in Assembly1
        // myValue = 10;
    }
}

await

It helps suspend evaluation of the enclosing async method until the asynchronous operation represented by its operand completes. On completion, it returns result of the operation if any.

It does not blocks the thread that evaluates async method, instead suspends the enclosing async method and returns to the caller of the method.

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class AwaitOperatorDemo
{
    // async Main method allowed since C# 7.1 
    public static async Task Main()
    {
        Task<int> downloading = DownloadProfileAsync();
        Console.WriteLine($"{nameof(Main)}: Started download.");

        int bytesLoaded = await downloading;
        Console.WriteLine($"{nameof(Main)}: Downloaded {bytesLoaded} bytes.");
    }

    private static async Task<int> DownloadProfileAsync()
    {
        Console.WriteLine($"{nameof(DownloadProfileAsync)}: Starting download.");

        var client = new HttpClient();
        // time taking call - await and move on
        byte[] content = await client.GetByteArrayAsync("https://learnbyinsight.com/about/");

        Console.WriteLine($"{nameof(DownloadProfileAsync)}: Finished download.");
        return content.Length;
    }
}

// Output:
// DownloadProfileAsync: Starting download.
// Main: Started download.
// DownloadProfileAsync: Finished download.
// Main: Downloaded 27700 bytes.

Default Interface methods

Now, we can add members to interfaces and provide a default implementation for those members. It helps in supporting backward compatibility. There would be no breaking change to existing interface consumers. Existing implementations inherit the default implementation.

public interface ICustomer
{
    DateTime DateJoined { get; }
    string Name { get; }

    // Later added to interface:
    public string Contact()
    {
       return "contact not provided";
    }
}

Wrap up

There are many more additions to C#. Believe, above are few that one should know and use in their day to day coding right away (if not already doing it). Most of it helps us with being more concise and avoid convoluted code.

Reference: https://docs.microsoft.com/en-us/dotnet/csharp/whats-new

Keep learning!

LearnByInsight
GitHub Profile Readme Samples

Quick look into SignalR

Last year, I was looking into various ways of communication between client and server for one of my project work. Evaluated SignalR too as one of the options. I found decent documentation online to put across a test app to see how it works.

Introduction

SignalR is a free and open-source software library for Microsoft ASP.NET that provides ability to server-side code push content to the connected clients in real-time.

Pushing data from the server to the client (not just browser clients) has always been a tough problem. SignalR makes it dead easy and handles all the heavy lifting for you.

https://github.com/SignalR/SignalR

Detailed documentation can be found at: https://dotnet.microsoft.com/apps/aspnet/signalr

Most of the shareout online considers it as ASP.NET/Web application solution only which is not true. As mentioned in quote above, client could be a non-browser too like a desktop application.

I gathered that behind the scenes, SignalR primarily tries to use Web Socket protocol to send data. WebSocket is a new HTML5 API (refer my detailed article on it) that enables bi-directional communication between the client and server. In case of any compatibility gap, SignalR uses other protocols like long polling.

P.S.: Since most of the code to make the test app was picked from web, all the credit to them. One specific source that I can recall: https://docs.microsoft.com/en-us/aspnet/signalr/overview/deployment/tutorial-signalr-self-host

Now, a quick peek into the SignalR test app
  • Using the SignalR Hub class to setup the server. Defined a hub that exposes a method like an end point for clients to send a message. Server can process the message and send back a response to all or few of the clients.
[HubName("TestHub")]
public class TestHub : Hub
{
    public void ProcessMessageFromClient(string message)
    {
        Console.WriteLine($"<Client sent:> {message}");

        // Do some processing with the client request and send the response back
        string newMessage = $"<Service sent>: Client message back in upper case: {message.ToUpper()}";
        Clients.All.ResponseToClientMessage(newMessage);
    }
}

  • Specify which “origins” we want to allow our application to accept. It is setup via CORS configuration. CORS is a security concept that allows end points from different domains to interact with each other.
public void Configuration(IAppBuilder app)
{
     app.UseCors(CorsOptions.AllowAll);
     app.MapSignalR();
}

  • Server is setup using OWIN (Open Web Interface for .NET). OWIN defines an abstraction between .NET web servers and web applications. This helps in self-hosting a web application in a process, outside of IIS.
static void Main(string[] args)
{
    string url = @"http://localhost:8080/";

    using (WebApp.Start<Startup>(url))
    {
        Console.WriteLine($"============ SERVER ============");
        Console.WriteLine($"Server running at {url}");
        Console.WriteLine("Wait for clients message requests for server to respond OR");
        Console.WriteLine("Type any message - it will be broadcast to all clients.");
        Console.WriteLine($"================================");

        // For server broadcast test
        // Get hub context 
        IHubContext ctx = GlobalHost.ConnectionManager.GetHubContext<TestHub>();

        string line = null;
        while ((line = Console.ReadLine()) != null)
        {
            string newMessage = $"<Server sent:> {line}";
            ctx.Clients.All.MessageFromServer(newMessage);
        }

        // pause to allow clients to receive
        Console.ReadLine();
    }
}

In above code, Using IHubContext:

  1. Server is setup to have earlier defined Hub as one of the broadcast end point.
  2. Server is also setup to broadcast any message to all clients by itself if needed be

  • Client is setup to communicate with the server (send and receive message) via hub using HubConnection & IHubProxy. Client can invoke the exposed end point in the hub to a send a message.
static void Main(string[] args)
{
    string url = @"http://localhost:8080/";

    var connection = new HubConnection(url);
    IHubProxy _hub = connection.CreateHubProxy("TestHub");
    connection.Start().Wait();

    // For server side initiation of messages
    _hub.On("MessageFromServer", x => Console.WriteLine(x));
    _hub.On("ResponseToClientMessage", x => Console.WriteLine(x));

    Console.WriteLine($"============ CLIENT ============");
    Console.WriteLine("Type any message - it will be sent as a request to server for a response.");
    Console.WriteLine($"================================");

    string line = null;
    while ((line = Console.ReadLine()) != null)
    {
        // Send message to Server
        _hub.Invoke("ProcessMessageFromClient", line).Wait();
    }

    Console.Read();
}

With above setup, we can see the communication between Client & Server realtime like below:

SignalR test

Things to consider while opting for SignalR

SignalR looks awesome. But, there are couple of things one should know while using it:

  • It’s a connected technology – each client connected through SignalR is using a persistent and dedicated connection on the Web Server. SignalR is shared as scalable but it never harms to look for any queries around connections, memory, cpu, etc with higher number of clients.
  • One would need to setup a valid host server with a PORT open on it that can be used for communication. This could depend on an organisation security protocols and approvals.

Hope this gives a quick overview about SignalR. Keep learning!

Download entire code for lookup from here: https://github.com/sandeep-mewara/SignalRTest

HttpClient single instance or multiple

Recently, we were working on a project that needed numerous HTTP requests to be made. Initial implementation had a new HttpClient object being created for every request being made. It looked to have some performance cost attached to it that led us to evaluate the effect of using single vs multiple instances of HttpClient.

Problem Statement:

Whats the best way to use HttpClient for multiple requests and the performance cost associated with it?

Assessment:

Went through the Microsoft documentation, which seemed updated based on last when I read few years back. Found a fineprint for myself that states:

HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors.

This was a straight give away that we should use a single instance HttpClient – irrespective of a usecase, one would want to keep distance from SocketException errors (though probability of it would be high for heavy usage of HTTP requests).

Now, the query was how to have single HttpClient for multiple requests but with different request payload for the calls? Also, does this has any impact on performance of the calls and if so, how much?

Resolution:

I started with looking into performance aspect for the two options. Created a test application that helped evaluate the time taken for various number of requests. Tried with www.google.com but seems they have some kind of check at 1000 requests so went ahead with www.bing.com that looked uniform till 5000 requests that I tried with.

for (var i = 0; i < noOfConnections; i++)
{
    using (var httpClient = new HttpClient())
    {
        var result = httpClient.GetAsync(new Uri("http://www.bing.com/")).Result;
    }
}
//having private static readonly HttpClient _httpClient = new HttpClient();
for (var i = 0; i < noOfConnections; i++)
{
    var result = _httpClient.GetAsync(new Uri("http://www.bing.com/")).Result;
}

With the above, I got the following numbers on an average post few runs:

No of RequestsMultiple Instance (s)Single Instance (s)%age Diff
1002016.6716.65
5001038814.56
100021617419.44
200043035118.37
5000103290612.21

It looked like the difference peaked around 1000 requests and overall there was an improvement with single instance.

Now, given we had a usecase where multiple HTTP requests has to be made simultaneously but with different payloads, looked at how to achieve it with single instance. Keeping multiple types of requests, unit testing, high load – One possible way looked like below that worked out well for us:

// Single instance of HttpClientManager was setup
public class HttpClientManager : IHttpClientManager
{
    ...
    public HttpClientManager(HttpMessageHandler messageHandler)
    {
        _httpClient = new HttpClient(messageHandler);
    }
    private HttpRequestMessage SetupRequest(IRequestPayload requestPayload)
    {
        var request = new HttpRequestMessage
        {
            RequestUri = new Uri(requestPayload.Url)
        };
        switch (requestPayload.RequestType)
        {
            case RequestType.POST_ASYNC:
                request.Method = HttpMethod.Post;
                request.Content = GetHttpContent(requestPayload.ContentJson);
                break;
            case RequestType.PUT_ASYNC:
                request.Method = HttpMethod.Put;
                request.Content = GetHttpContent(requestPayload.ContentJson);
                break;
            case RequestType.DELETE_ASYNC:
                request.Method = HttpMethod.Delete;
                break;
            case RequestType.GET_ASYNC:
                request.Method = HttpMethod.Get;
                break;
            default:
                request.Method = HttpMethod.Get;
                break;
        }
        ...
    }
    public HttpResponseMessage ExecuteRequest(IRequestPayload requestPayload)
    {
        HttpRequestMessage httpRequestMessage = SetupRequest(requestPayload);
        HttpResponseMessage httpResponseMessage = _httpClient.SendAsync(httpRequestMessage, HttpCompletionOption.ResponseHeadersRead).Result;
        return httpResponseMessage;
    }
    private HttpContent GetHttpContent(string contentJson)
    {
        return new StringContent(contentJson, ENCODING, MEDIATYPE_JSON);
    }
}

Since there are numerous articles on the web explaining details of the entire HttpClient workflow and inner details, I will not cover that here but a quick explanation on couple of key info. In the code above:

HttpRequestMessage is used to setup HttpClient object based on our need. We make use of the fact that HttpRequestMessage can be used only once. After the request is sent, it is disposed immediately to ensure that any associated Content object is disposed.

Making use of HttpClient underlying implementation, have used HttpMessageHandler more from the unit test point of view.

Conclusion:

One should use a single instance of HttpClient at application level to avoid create/destroy of it multiple times. Further, results suggest this also has better performance with more than 12% improvement based on the load.

For multiple requests of different payloads, having a single instance HttpClient but a new HttpRequestMessage for every request looked a good approach to use.

P.S.: For .NET Core, Microsoft added a new interface around the same discussion to have better handle at HttpClient instance: https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests

Entire code for lookup can be downloaded from here.

Microsoft Products Retirement

Earlier, I was not sure if I can share the information outside, but got a confirmation today that I can.
Microsoft shared the following information with us in order to be better prepared for the upcoming year.
These are the Microsoft products that are going to retire this year and be End Of Life, meaning – End of support.

Product End Of Life Date
SQL Server 2000 4/9/2013
Commerce Server 2002 7/9/2013
BizTalk Server 2004 7/8/2014
Project Server 2003 4/8/2014
Live Communication Server 2003 1/14/2014
Office 2003 4/8/2014
Windows XP 4/8/2014
.NET Framework 1.1 10/8/2013
Visual Studio .NET 2003 10/8/2013

It is suggested by Microsoft that we migrate to newer version if we are using any one of these products.
So please have a look at what version you are working on currently and take necessary action if needed.