Detecting Sync over Async Code in ASP.NET Core

Sync over Async

It’s pretty easy to write some bad async code, especially when you first start using async/await. Async/await is pretty viral in .NET, which means it generally goes all the way through the stack. This can be challenging if you are trying to add async/await to an existing app and you usually end up adding sync over async code.

If you don’t use async/await correctly, and end up writing sync-over-async code, you’ll ultimately end up causing ThreadPool starvation.

Sync over Async

The term refers to making an async call but not awaiting it. Often time this is caused by calling .Wait() or .Result on the returned Task.

Ben.BlockingDetector

Ben Adams wrote a Blocking Detector for ASP.NET Core.

Start by adding the NuGet package Ben.BlockingDetector to your csproj.

At the very beginning (or the higher the better) of your Configure() method in your Startup, add the UseBlockingDetection() extension method to the IApplicationBuilder.

That’s it. Really. Now when we run our application and hit the /sync-over-async route from the example above, a warning is logged in the console (or however you have logging configured).

I’ve added the red arrow to point out our sync-over-async method in the call stack.

Microsoft.VisualStudio.Threading.Analyzers

Another great tool is the Microsoft.VisualStudio.Threading.Analyzers NuGet Package.

Static code analyzer to detect common mistakes or potential issues regarding threading and async coding.

Simply add it the PackageReference to your csproj and by default, you will immediately be getting warnings about sync over async calls. Here’s a screenshot in JetBrains Rider (which also can use Roslyn analyzers) that is notifying us of the issue.

Are you using any other analyzers or packages to detect blocking or problematic async code? Let me know in the comments or on Twitter.

Related Posts: I’ve also written a post on Lazy Async which try’s to solve the issue of deferring doing IO until it’s first needed.

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.

Roundup #52: .NET Core and systemd, System.Threading.Channels, screencastR, Configuration Pitfalls

Here are the things that caught my eye recently in .NET.  I’d love to hear what you found most interesting this week.  Let me know in the comments or on Twitter.

.NET Core and systemd

In preview7 a new package was added to the Microsoft.Extensions set of packages that enables integration with systemd. For the Windows focused, systemd allows similar functionality to Windows Services, there is a post on how to do what we discuss here for Windows Services in this post. This work was contributed by Tom Deseyn from Red Hat. In this post we will create a .NET Core app that runs as a systemd service. The integration makes systemd aware when the application has started/is stopping, and configures logs to be sent in a way that journald (the logging system of systemd) understands log priorities.

Link: https://devblogs.microsoft.com/dotnet/net-core-and-systemd/

An Introduction to System.Threading.Channels

I’ve recently begun making use of a relatively new (well, it’s a little over a year old at the time of writing) feature called “Channels”. The current version number is 4.5.0 (with a 4.6.0 preview also available as pre-release) which makes it sound like it’s been around for a lot longer, but in fact, 4.5.0 was the first stable release of this package!

In this post, I want to provide a short introduction to this feature, which I will hopefully build upon in later posts with some real-world scenarios explaining how and where I have successfully applied it.

Link: https://www.stevejgordon.co.uk/an-introduction-to-system-threading-channels

screencastR – Simple screen sharing app using SignalR streaming

In this article, we will see how to create simple screen sharing app using signalR streaming. SignalR supports both server to client and client to server streaming. In my previous article , I have done server to client streaming with ChannelReader and ChannelWriter for streaming support. This may look very complex to implement asynchronous streaming just like writing the asynchronous method without async and await keyword. IAsyncEnumerable is the latest addition to .Net Core 3.0 and C# 8 feature for asynchronous streaming. It is now super easy to implement asynchronous streaming with few lines of clean code. In this example, we will use client to server streaming to stream the desktop content to all the connected remote client viewers using signalR stream with the support of IAsyncEnumerable API.

Link: https://jeevasubburaj.com/2019/08/13/screencastr-simple-screensharing-app-using-signalr-streaming/

Avoiding ASP.Net Core Configuration Pitfalls With Array Values

ASP.NET Core continues to improve on the legacy of the .NET Framework. Our team is impressed with its performance and excited about future possibilities, but change is seldom a smooth transition. In this post, I’ll explain a pitfall you may run into using the newest configuration model in .NET Core and options to mitigate the issue.

Link: https://rimdev.io/avoiding-aspnet-core-configuration-pitfalls-with-array-values/

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.

Custom Metrics to AWS CloudWatch from ASP.NET Core

CloudWatch Custom Metrics

I was playing around with AWS CloudWatch and was curious to send custom metrics from ASP.NET Core. Specifically the execution time of an HTTP request.

AWS SDK

I created a simple middleware that starts a StopWatch before calling the next middleware in the pipeline. When it returns, stop the StopWatch and send the data to CloudWatch.

First is to add the relevant NuGet packages.

Configuration

If you’ve never used the AWS SDK/Packages, I recommend checking out my post on Configuring AWS SDK in ASP.NET Core. It goes over creating a named profile to store your AWS credentials and using appSettings or Environment variables to pass them through to ASP.NET Core.

Middleware

Next is to create a simple middleware using the SDK. The middleware is having the IAmazonCloudwatch injected into the constructor. In the Startup’s ConfigureServices is where this is configured.

We’re simply calling the PutMetricDataAsync with a list of one MetricDatum. It contains the metric name, value, unit, timestamp, and dimensions.

Startup

As mentioned, in order to use the AWS SDK and the IAmazonCloudWatch in the middleware, you can use the AddDefaultAWSOptions and AddAWSService<IAmazonCloudWatch> to ConfigureServices to register the appropriate types.

Results

If you look in CloudWatch, you can now see the new custom metrics we’ve published.

Next

Before you start using this in a production environment, there are a couple of glaring issues.

First, sending the metrics to AWS, although incredibly fast should be handled outside of the actual HTTP request. this can be done completely asynchronously from the actual request. There is no point in delaying the HTTP response to the client. To solve this, we’ll add a queue and do it in a background service.

Secondly, some of the cost associated with CloudWatch is based on the number of API calls. This is why there is a List<MetricDatum> in the PutMetricDataRequest. It allows you to send/batch multiple metrics together to limit the number of API calls.

This is a better solution is to collect PutMetricDataRequest separately and send them in batch in a background service.

More on that coming soon.

Enjoy this post? Subscribe!

Subscribe to our weekly Newsletter and stay tuned.