+61 450 303 656 info@newplanetit.com
C# Async Tips & Tricks

C# Async Tips & Tricks

The following are few tips and tricks for working with async in C#. This is as much a reference for myself as anyone else, but I figured it would probably useful for others as well.

Run sync method as “async”

Technically, this is fake async. It’s still blocking, but it runs on a background thread. This is really only useful to keep from blocking the UI thread with desktop/mobile applications. In a web application context, this is pretty much pointless, since every thread comes from the same pool for serving requests that the main (request) thread came from and the response won’t be returned until everything is done anyways.

Run async method as sync

For this one we have a helper class borrowed from Microsoft. It appears is various namespaces, but always as an internal, so you can’t just use it directly from the framework.



Discarding the context

When you await an asynchronous operation, the context of the calling code is passed along by default. This can have a not insignificant performance impact. If you don’t need to restore that context later, then it’s just wasted resources. You can prevent this behavior by appending ConfigureAwait(false) to your call:

You should pretty much always do this, unless there’s a specific reason to keep the context. Certain scenarios for that include when you need access to a particular GUI component or you need to return a response from a controller action.

Importantly, though, each operation has it’s own context, so you can safely use ConfigureAwait(false) inside an asynchronous method called by code that needs to maintain the context; you just wouldn’t be able to use ConfigureAwait(false) on that method itself. For example:

As a result, you can and should factor out multiple asynchronous operations where context needs to be maintained into a separate method, so you’re only need to conserve the context once, instead of N times. For example:

Here, each of these operations get a copy of the calling code’s context, and since we need that context, using ConfigureAwait(false) is not an option. However, by refactoring to the following code, we’d only need a single copy of the calling code’s context.


Async and garbage collection

In synchronous code, local variables go on the stack and are discarded when they go out of scope. However, because of the context switching that occurs when you await an async operation, those local variables have to be preserved. The Framework does this by adding them to a struct that goes on the heap. In this way, when execution is returned to the calling code, the locals can be restored. However, the more you have going on in your code, the more has to be added to the heap, resulting in more frequent GC cycles. Some of this may be unavoidable, but you should watch for useless variable assignments when you’re going to be awaiting an async operation. For example, code like:

This will cause two different values to go into the heap, whereas if all you need is todayString, you can reduce that to one value simply by rewriting the code as:

It’s one of those things you don’t think about unless someone tells you.

Cancelling async work

One of the benefits of async in C# is that tasks can be cancelled. This allows you to abort a task if user cancels it in the UI, navigates away from a web pages, etc. To enable cancellation, your asynchronous methods should accept a CancellationToken parameter.

That cancellation token, then, should be passed into any other asynchronous operations the method calls. It is the responsibility of the method to enable cancellation, if it can and desires to. Not all asynchronous tasks can be cancelled. Generally speaking, whether a task can be cancelled or not depends on whether the method has an overload that accepts CancellationToken.

Cancelling tasks that can’t be cancelled

In some scenarios, you can still cancel a task if the method doesn’t provide an overload that accepts CancellationToken. You’re not truly cancelling the task, but depending on the implementation, you may be able to abort it, nonetheless, effectively having the same result. For example, the ReadAsStringAsync method of HttpContent does not have an overload that accepts CancellationToken. However, if you dispose of the HttpResponseMessage, then the attempt to read the content will be aborted.

Essentially, we’re using the CancellationToken to call Dispose on the HttpResponseMessage instance, if it’s cancelled. That will then cause ReadAsStringAsync to throw an ObjectDisposedException. We catch this exception, and if the CancellationToken has been canceled, we throw an OperationCanceledException instead.

The key to this approach is really in the ability to dispose of some parent object that will cause the method that can’t be cancelled to raise an exception. It’s not applicable to everything, but can give you an out in certain scenarios.

Eliding the async/await keywords

An asynchronous method can be written in either of the following ways:

In the first, the asynchronous operation is awaited in the method, and the result is then wrapped in another task before being returned to the calling code. In the second, the task for the asynchronous operation is returned directly. If you have an asynchronous method that only calls another asynchronous method (as is often the case with asynchronous overloads), then you should elide the async/await keywords, as in the second method above.

Handle exceptions in async methods

Methods with the async keyword can safely throw exceptions. The compiler will take care of wrapping the exception in a Task.

However, Task-returning methods without the async keyword should return a Task with the exception.


Reducing duplicate code when implementing sync and async versions of a method

Often when developing sync and async versions of a method, you’ll find that the only real difference between the two implementations is that one calls async versions of various methods while the other calls the sync versions. When the implementation is virtually the same, except for the use of async/await, there’s various “hacks” you can utilize to factor out the duplicate code. The best and least “hacky” method I’ve found is referred to as the “Flag Argument Hack”. Essentially, you introduce a boolean that indicates whether the method should use sync or async access and then branch accordingly:

That seems like a lot of code, so let’s unwrap it a bit. First, we have a private method GetStringCoreAsync. This is where we factor out our common code. Here, we’re just calling into some other library that has sync and async methods to get some sort of string. Admittedly, for something this simplistic, you really shouldn’t employ this hack, but should rather just have each method call its appropriate counterpart directly. However, I didn’t want to hinder understanding by introducing an overly complex implementation. As you can see, the main point here is that we’re branching on the value of sync to either utilize the sync or async method from the library. This will work fine as long as you await the async method, which then means that this private method needs to have the async keyword. We’re also passing in a CancellationToken in case the async methods employed inside are cancellable.

Next, we just have our sync and async implementations which merely call the private method. For the sync version, we need to unwrap the Task being returned from the private method. To do that, we use the GetAwaiter().GetResult() pattern to safely block on the async call. There’s no danger of a deadlock here, because while the private method is async, when we pass true for sync, no async methods are actually employed. We also use ConfigureAwait(false) to prevent the synchronization context from being attached, since it’s entirely unnecessary bloat: there’s no possibility of thread-switching here.

The async implementation is fairly unremarkable. There’s an overload that passes a default of CancellationToken.None in case no cancellation token is passed, and then the actual implementation just calls the private method with false for the sync parameter and includes the cancellation token.

There’s a school of thought that says that methods shouldn’t branch on booleans like this. If you have two separate sets of logic, then you should have two separate methods. There’s some truth in that, but I think it has to be weighed against how different the logic actually is. As a result, this is a good way to factor out common code if you have a significant amount of logic that is mostly duplicated. However, it should be a last resort in this respect. If there’s portions of the code that are CPU-bound or otherwise run synchronously, you should first try to factor out just these portions of code. You may still have some duplication between your sync and async methods, but if you can get most of the meat out into methods that are usable by either without resorting to hacks, then that’s the optimal path.

There’s also an argument to be made that if you have that much logic, your method might be doing too much in the first place. You’ll have to let your own judgement rule. There are times when doing something like this is actually the best path, but you should carefully evaluate whether that’s the case before simply employing this method.

Async in console applications

For what it’s worth, C# 7.1 promises Async Main support, so you’d simply do:

However, at the time of writing, this doesn’t work. It’s really just syntactic sugar, though. When the compiler encounters an async Main, it simply wraps it in a regular synchronous Main, just like in the first code sample.

Ensuring that async doesn’t block

There’s whole lot of terminology that gets confused with async in C#. You hear that sync code blocks the thread, while async code does not. That’s actually not true. Whether or not a thread is blocked, really has nothing at all to do with whether is sync or async. The only reason it comes into the discussion at all is that async is at least better than sync if your goal is to not block a thread, because sometimes, in some scenarios, it maybe might just run on a different thread. If you have any synchronous code in your async method (anything that’s not awaiting something else) that code will always run sync. Further, an async operation may run sync if what it awaits on has already completed. Lastly, async doesn’t ensure that the work won’t actually be done on the same thread. It just opens up the possibility for a thread-switch.

Long and short, if you need to ensure that an async operation will not block the thread, such as for a desktop or mobile app where you want to keep the GUI thread open, then you should use:

Wait. Isn’t that the same thing we used above to run sync as “async”? Yep. The same principle applies: Task.Run will run the delegate you pass to it on a new thread. In turn, that means it won’t run on the current thread.

Making a sync operation Task-compatible

Most async methods return Task, but not all Task-returning methods are necessarily async. That can be a bit of a mind-bender. Let’s say you need to implement an a method that returns Task or Task<TResult>, but you don’t actually have anything async to do.

First, this ensures that the operation hasn’t been canceled. If it has, a canceled task is returned. Then, the sync work we need to do is wrapped in a try..catchblock. If an exception is thrown, we’ll need to return a faulted task, which includes that exception. Finally, if it completes correctly, we return a completed task.

It’s important to realize that this is not actually async. DoSomething is still sync and will block. However, now it can be handled as if it was async, because it returns a task, as it should. Why would you do this? Well, one example is when implementing an adapter pattern and one of the sources you’re adapting to doesn’t offer an async API. You still have to satisfy the interface, but you should comment the method to notate that it’s not actually async. Those wanting to utilize this method in situations where they need to not block the thread can choose to call it via passing it as a delegate to Task.Run.

Tasks return “hot”

One aspect of async programming in C# that’s not immediately obvious is that tasks return “hot”, or already started. The await keyword serves to halt the code until the task is completed, but doesn’t actually start it. This becomes really interesting when you look at the effects on running tasks in parallel.

Here, the three tasks run in serial. Only after FooAsync completes does BarAsync start, and likewise, BazAsync will not start until BarAsync completes. This is due to the tasks being awaited inline. Now, consider the following code:

Here, the tasks now run in parallel. This is due to the fact that all three are started before all three are subsequently awaited, again, because they return hot.

This can seem a little counter-intuitive considering that Task.WhenAll exists. Why is that functionality necessary if all the tasks are already running? Simply, Task.WhenAll exists as a way to await the completion of a set of tasks, so that the code does not proceed until all the results are ready.

Since both tasks need to be completed before we can run the multiplication line, we can halt until both are complete by await Task.WhenAll. Otherwise, it doesn’t really matter. In fact, you can forgo Task.WhenAll even here if you await both tasks instead of calling Result directly:

Long and short, it’s really just a matter of taste more than anything. Still, it’s important to realize that tasks start immediately and it’s not the act of awaiting them that causes them to start. Rather, awaiting simply prevents the code from moving on until the task completes.


Our Blog

Here is the useful programming tips and tricks.  

C# Async Tips & Tricks

The following are few tips and tricks for working with async in C#. This is as much a reference for myself as anyone else, but I figured it would probably useful for others as well. Run sync method as "async" [crayon-5d8220664f7bb713014884/] Technically, this is fake...


Our Blog Here is the useful programming tips and tricks.  30,000+ Avid Subscribers

New Feature in Angular 6

The 6.0.0 release of Angular is here! This is a major release focused less on the underlying framework, and more on the toolchain and on making it easier to move quickly with Angular in the future. As a part of this release, we are synchronizing the major...

Remove duplicate records from a table in SQL Server

Sometimes we required to remove duplicate records from a table although table has a UniqueID Column with identity. In this article, I would like to share a best way to delete duplicate records from a table in SQL Server. Suppose we have below Employee...

Sharing Data Between Angular Components – Four Methods

Health Check: This lesson was last reviewed on May 30, 2018 and tested with these packages: Angular v6.0.3 RxJS v6.2 Update Notes: Changed imports for RxJS v6.2 Data sharing is an essential concept to understand before diving into your first Angular...

Guards and Login Redirects in Angular

Redirect the user to the page they landed on before being forced to login In your web application, you likely require a user to login to access some functionality. With Angular, we can implement this flow using route guards and the router to help manage redirects....


Avid Subscribers

New Feature in Angular 6

New Feature in Angular 6

The 6.0.0 release of Angular is here! This is a major release focused less on the underlying framework, and more on the toolchain and on making it easier to move quickly with Angular in the future.

As a part of this release, we are synchronizing the major versions going forward for the framework packages (@angular/core@angular/common@angular/compiler, etc), the Angular CLI, and Angular Material + CDK. All are releasing as 6.0.0 today. We made this change to clarify cross compatibility. The minor and patch releases for these projects will be issued based on the project’s needs.

See the full list of changes in our changelogs: frameworkmaterial+cdkcli.

ng update

ng update <package> is a new CLI command that analyzes your package.json and uses its knowledge of Angular to recommend updates to your application. To see it in action, check out our update guide.

Not only will ng update help you adopt the right version of dependencies, and keep your dependencies in sync, but 3rd parties can provide update scripts using schematics. If one of your dependencies provides an ng updateschematic, they can automatically update your code when they need to make breaking changes!

ng update will not replace your package manager, but uses npm or yarn under the hood to manage dependencies. In addition to updating dependencies and peer dependencies, ng update will apply needed transforms to your project.

For example, the command ng update @angular/core will update all of the Angular framework packages as well as RxJS and TypeScript, and will run any schematics available on these packages to keep you up to date. As part of this one command, we’ll automatically install rxjs-compat into your application to make the adoption of RxJS v6 smoother.

We expect to see many more libraries and packages add ng updateschematics over the coming months, and have already heard from enterprise component library teams that are planning to use ng update to push through important changes in an automated way to save their developers time.

Learn more about how the ng update command works. To get started creating your own ng update schematic, take a look at the entry in the package.json of rxjs and its associated collection.json.

ng add

Another new CLI command ng add <package> makes adding new capabilities to your project easy. ng add will use your package manager to download new dependencies and invoke an installation script (implemented as a schematic) which can update your project with configuration changes, add additional dependencies (e.g. polyfills), or scaffold package-specific initialization code.

Try out some of the following on your fresh ng new application:

  • ng add @angular/pwa — Turn your application into a PWA by adding an app manifest and service worker
  • ng add @ng-bootstrap/schematics — Add ng-bootstrap to your application
  • ng add @angular/material — Install and setup Angular Material and theming and register new starter components into ng generate
  • ng add @clr/angular@next— Install and setup Clarity from VMWare
  • ng add @angular/elements — Add the needed document-register-element.js polyfill and dependencies for Angular Elements (see below)

Because ng add is built on top of schematics and the npm registry, our hope is that libraries and the community will help us build a rich ecosystem of ng add supporting packages.

Take a look at Angular Material’s ng-add schematic for an example to help you get started building your own ng-add schematics.

Angular Elements

The first release of Angular Elements is focused on allowing you to bootstrap Angular components within an existing Angular application by registering them as Custom Elements. We use this extensively in angular.io as part of our content management system to allow dynamic bootstrapping of capabilities via embedded HTML. This replaces the need to manually bootstrap Angular components found in static html content.

Check out an example of registering a component as a custom element or learn more about Angular Elements.

One of our community members has also produced an Angular Elements Quick Start video that we highly recommend.

Angular Material + CDK Components

The biggest addition is the new tree component for displaying hierarchical data. Following patterns from the data-table component, the CDK houses the core tree directives, with Angular Material offering the same experience with Material Design styles on top. We recently gave a talk about the component, so check that out for more information (videoslides). These new tree components come in both styled (Material’s mat-tree) and unstyled versions (CDK’s cdk-tree).

Alongside the tree, we also have new badge and bottom-sheet components. Badges help display small bits of helpful information, such as unread item counts. Bottom-sheets are a special type of mobile-centric dialogs that come up from the bottom of the viewport, commonly used to present a list of options following an action.

The @angular/cdk/overlay package is one of the most powerful pieces of infrastructure in the CDK today. With the release of v6, this package now includes new positioning logic that helps make pop-ups that intelligently remain on-screen in all situations.

Angular Material Starter Components

Once you have run ng add @angular/material to add material to an existing application, you will also be able to generate 3 new starter components.

Material Sidenav

You can now generate a starter component including a toolbar with the app name and the side navigation. This component is responsive based on breakpoints.


ng generate @angular/material:material-nav --name=my-nav

This will create this starter component:

Material Dashboard

You can now generate a starter dashboard component containing a dynamic grid list of cards.


ng generate @angular/material:material-dashboard --name=my-dashboard

This will create this starter component:

Material Data Table

You can generate a starter data table component that is pre-configured with a datasource for sorting and pagination.


ng generate @angular/material:material-table --name=my-table

This will create this starter component:

CLI Workspaces

CLI v6 now has support for workspaces containing multiple projects, such as multiple applications or libraries. CLI projects will now use angular.jsoninstead of .angular-cli.json for build and project configuration.

Each CLI workspace has projects, each project has targets, and each target can have configurations.

Library Support

One of the most requested features for our CLI has been support for creating and building libraries, and we are proud to introduce:

ng generate library <name>

This command will create a library project within your CLI workspace, and configure it for testing and for building.

Learn more about creating libraries with the Angular CLI

Tree Shakable Providers

To make your applications smaller, we’ve moved from modules referencing services to services referencing modules. This allows us to only bundle services into your code base in modules where they are injected.



No references are needed in our NgModule.

Animations Performance Improvements

We’ve updated our implementation of Animations to no longer need the web animations polyfill. This means that you can remove this polyfill from your application and save approximately 47KB of bundle size, while increasing animations performance in Safari at the same time.

RxJS v6

Angular has been updated to use v6 of RxJS. RxJS is an independent project that released v6 several weeks ago. RxJS v6 brings with it several major changes, along with a backwards compatibility package rxjs-compat that will keep your applications working.

RxJS has been rearranged to make it more tree-shakable, ensuring that only the pieces of RxJS that you use are included in your production bundles.

If you use ng update, your application should keep working, but you can learn more about the 5.5 to 6.0 migration.

Long Term Support (LTS)

We are expanding our Long Term Support to all major releases.

Previously we announced that only v4 and v6 would be LTS releases but in order to make updating from one major to the next easier, and give bigger projects more time to plan updates, we have decided to extend the long-term support to all major releases starting with v4.

Each major release will be supported for 18 months with around 6 months of active development followed by 12 months of critical bugfixes and security patches.

Learn more about how Angular versions and releases.

How to update to 6.0.0

Visit update.angular.io for information and guidance on updating your application.

The update generally follows 3 steps, and will take advantage of the new ng update tool.

  1. Update @angular/cli
  2. Update your Angular framework packages
  3. Update other dependencies

Making it easy for developers to stay up to date with the latest releases is extremely important to us, so let us know what you think about this release in the comments!

What about Ivy?

At ng-conf we mentioned a new initiative called Ivy — our next generation rendering pipeline. Ivy is currently under active development and is not part of the 6.0 release. We will announce an opt-in preview of Ivy as soon as it is ready in the coming months. Keep an eye on this blog for the latest information.

Remove duplicate records from a table in SQL Server

Remove duplicate records from a table in SQL Server

Sometimes we required to remove duplicate records from a table although table has a UniqueID Column with identity. In this article, I would like to share a best way to delete duplicate records from a table in SQL Server.

Suppose we have below Employee table in SQL Server.

The data in this table is as shown below:

Remove Duplicate Records by using ROW_NUMBER()

For more help about ROW_NUMBER(), please follow the MSDN link.


In this article, I expose how can you remove duplicate records from a table in SQL Server. I hope after reading this article you will be able to use these tips. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article.

Sharing Data Between Angular Components – Four Methods

Sharing Data Between Angular Components – Four Methods

Health Check: This lesson was last reviewed on  and tested with these packages:

  • Angular v6.0.3
  • RxJS v6.2

Update Notes: Changed imports for RxJS v6.2

Data sharing is an essential concept to understand before diving into your first Angular project. In this lesson, I provide four different methods for sharing data between Angular components.

The Parent-Child-Sibling structure of our Angular app.

Parent to Child: Sharing Data via Input


This is probably the most common and straightforward method of sharing data. It works by using the @Input() decorator to allow data to be passed via the template.

# parent.component.ts

# child.component.ts

Child to Parent: Sharing Data via ViewChild

ViewChild allows one component to be injected into another, giving the parent access to its attributes and functions. One caveat, however, is that child won’t be available until after the view has been initialized. This means we need to implement the AfterViewInit lifecycle hook to receive the data from the child.

# parent.component.ts

# child.component.ts

Child to Parent: Sharing Data via Output() and EventEmitter

Another way to share data is to emit data from the child, which can be listed to by the parent. This approach is ideal when you want to share data changes that occur on things like button clicks, form entires, and other user events.

In the parent, we create a function to receive the message and set it equal to the message variable.

In the child, we declare a messageEvent variable with the Output decorator and set it equal to a new event emitter. Then we create a function named sendMessage that calls emit on this event with the message we want to send. Lastly, we create a button to trigger this function.

The parent can now subscribe to this messageEvent that’s outputted by the child component, then run the receive message function whenever this event occurs.

# parent.component.ts

# child.component.ts

Unrelated Components: Sharing Data with a Service

When passing data between components that lack a direct connection, such as siblings, grandchildren, etc, you should you a shared service. When you have data that should always be in sync, I find the RxJS BehaviorSubject very useful in this situation.

You can also use a regular RxJS Subject for sharing data via the service, but here’s why I prefer a BehaviorSubject.

  • It will always return the current value on subscription – there is no need to call onnext
  • It has a getValue() function to extract the last value as raw data.
  • It ensures that the component always receives the most recent data.

In the service, we create a private BehaviorSubject that will hold the current value of the message. We define a currentMessage variable handle this data stream as an observable that will be used by the components. Lastly, we create a function that calls next on the BehaviorSubject to change its value.

The parent, child, and sibling components all receive the same treatment. We inject the DataService in the constructor, then subscribe to the currentMessage observable and set its value equal to the message variable.

Now if we create a function in any one of these components that changes the value of the message. when this function is executed the new data it’s automatically broadcast to all other components.

# data.service.ts

# parent.component.ts

# sibling.component.ts

Guards and Login Redirects in Angular

Guards and Login Redirects in Angular

Redirect the user to the page they landed on before being forced to login

In your web application, you likely require a user to login to access some functionality. With Angular, we can implement this flow using route guards and the router to help manage redirects.

Basic Route Guard

Imagine we’re building a forum, and we want to ensure that a user is logged in before they can post a new message. You could have the following routes in your application.

The route to the post is the one we want to protect, as we want to allow people to read forums without being logged in. To protect it, we’ll need to create a route guard, which allows us to run a check (or any number of checks) before a route is activated.

There are several types of guards, but the one we’ll use is the canActivate type, which is run before you navigate to a route. These are created like any other service, but they must implement the canActivate method. Here is one such example.

Once we attach this guard to a route, the canActivate() method will fire before the route is activated. The logic will first check if the user is valid (using whatever logic you might need), and if not it will navigate to the login route. Note it also grabs the current URL and sets is as a query parameter, so it would be something like /login?return=%2Fforums%2F2-introductions (which the route becomes URL encoded). Now, we can attach this guard to our route.

A route can have multiple guards, so you must assign a new property on the route with an array of guards. Each type of guard has its own property that you’ll use.

The last bit is to redirect the user after login, which is handled in the login component. This component has a login() method that handles authentication logic, and once authenticated it will redirect you.

Here we use navigateByUrl() to handle the redirect navigation. This takes a raw URL and routes to it, instead of using the typical naviate() method that takes an array of paths.

There are certainly a number of ways to customize this flow for your own purposes. For example, you could store the return URL in a cookie or localstorage instead. I personally like using the URL because I believe that is where navigation state should be captured.