skip to Main Content

I am trying to force an asp.net app to be single threaded ie: can only serve one request at time (need to do this to simulate a legacy application).

All I could think of was use a static variable to lock and Monitor.TryEnter and sleep the thread for 5 seconds to simulate as through there is only one thread processing requests.

Is there a better/elegant way to force an asp.net app to be single threaded only ie: able to strictly process one request only at a time.

This will be run as Docker container with Kestrel serving the requests.

This is what I have so far that seems to work, when calling the /test enpoint it blocks the whole app for 5 seconds

public class Program
{
    private static readonly object LockObject = new();

    public static void Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddAuthorization();

        builder.Services.AddEndpointsApiExplorer();
        builder.Services.AddSwaggerGen();

        builder.Services.AddApplicationInsightsTelemetry();


        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseSwagger();
            app.UseSwaggerUI();
        }

        app.UseAuthorization();

        app.MapGet("/test", (HttpContext httpContext) =>
        {
            if (Monitor.TryEnter(LockObject, new TimeSpan(0, 0, 6)))
            {
                try
                {
                    Thread.Sleep(5000);
                }
                finally
                {
                    Monitor.Exit(LockObject);
                }
            }

            return ("Hello From Container: " + System.Environment.MachineName);
        });

        app.Run();
    }
}

2

Answers


  1. if you application is hosted on iis
    in application selected the pool for application

    click in Advanced Settings
    Option Queue Length: 1

    enter image description here

    look at https://docs.revenera.com/installshield23helplib/helplibrary/IIS-AppPoolsNode.htm

    if you are running from iis express

    IIS Express can be configured using applicationHost.config file. It is located at %userprofile%my documentsIISexpressconfig

    look in this post Configure Maximum Number of Requests in IIS Express

    In kestrel

    builder.WebHost.ConfigureKestrel(serverOptions =>
    {
       serverOptions.Limits.MaxConcurrentConnections = 1;
    });
    

    more info https://learn.microsoft.com/en-us/aspnet/core/fundamentals/servers/kestrel/options?view=aspnetcore-6.0

    Login or Signup to reply.
  2. You can use the ConcurrencyLimiter middleware to limit concurrent requests.

    Though, to be clear, this isn’t single threaded, it’s single request at a time.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search