Przeglądaj źródła

[C#][aspnetcore] feat - Upgrade to .NET 6 LTS (#6914)

* [aspnetcore-corert] Upgrade Npgsql

Brings CoreRT in sync with https://github.com/TechEmpower/FrameworkBenchmarks/pull/6863.

* Delete RD.XML

* Enable SSE 4.2

* feat - Upgrade to .NET 6 LTS

* corert upgrade

* aspnetcore-mono upgrade

* Added editorConfig

* Refactoring.
1. Enabled ImplicitUsings.
2. File Scoped Namespaces.

* corert refactoring

* Refactoring missed files

* chore - upgrade package versions

* Revert "aspnetcore-mono upgrade"

This reverts commit d3d55ea917e38abfbea286050f6e956abd5d910e.

* fix - Keep consistent style changes between corert and core one

* chore (files) - Fix inconsistent whitespace between project files

* fix - Added missing namespace

* Added missing usings

Co-authored-by: Michal Strehovský <[email protected]>
Shreyas Jejurkar 3 lat temu
rodzic
commit
3b1a34487f
100 zmienionych plików z 2804 dodań i 3077 usunięć
  1. 8 0
      frameworks/CSharp/.editorconfig
  2. 36 38
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/AsciiString.cs
  3. 5 6
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.Caching.cs
  4. 140 144
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.HttpConnection.cs
  5. 19 20
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.Json.cs
  6. 15 16
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.Plaintext.cs
  7. 103 104
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.cs
  8. 36 42
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkConfigurationHelpers.cs
  9. 44 45
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BufferExtensions.cs
  10. 99 101
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BufferWriter.cs
  11. 5 6
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Configuration/AppSettings.cs
  12. 7 8
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Configuration/DatabaseServer.cs
  13. 28 31
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/BatchUpdateString.cs
  14. 6 7
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/CachedWorld.cs
  15. 11 14
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/Fortune.cs
  16. 5 6
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/JsonMessage.cs
  17. 17 20
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/Random.cs
  18. 6 7
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/World.cs
  19. 43 45
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/DateHeader.cs
  20. 14 15
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/HttpApplication.cs
  21. 6 8
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/IHttpConnection.cs
  22. 6 6
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/PlatformBenchmarks.csproj
  23. 46 52
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Program.cs
  24. 3 7
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Startup.cs
  25. 36 38
      frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/StringBuilderCache.cs
  26. 2 2
      frameworks/CSharp/aspnetcore-corert/aspcore-corert-ado-pg-up.dockerfile
  27. 2 2
      frameworks/CSharp/aspnetcore-corert/aspcore-corert-ado-pg.dockerfile
  28. 2 2
      frameworks/CSharp/aspnetcore-corert/aspcore-corert.dockerfile
  29. 5 4
      frameworks/CSharp/aspnetcore/Benchmarks/Benchmarks.csproj
  30. 5 6
      frameworks/CSharp/aspnetcore/Benchmarks/Configuration/AppSettings.cs
  31. 7 8
      frameworks/CSharp/aspnetcore/Benchmarks/Configuration/ConsoleArgs.cs
  32. 53 59
      frameworks/CSharp/aspnetcore/Benchmarks/Configuration/ConsoleHostScenariosConfiguration.cs
  33. 7 8
      frameworks/CSharp/aspnetcore/Benchmarks/Configuration/DatabaseServer.cs
  34. 8 11
      frameworks/CSharp/aspnetcore/Benchmarks/Configuration/EnabledScenario.cs
  35. 4 5
      frameworks/CSharp/aspnetcore/Benchmarks/Configuration/IScenariosConfiguration.cs
  36. 107 112
      frameworks/CSharp/aspnetcore/Benchmarks/Configuration/Scenarios.cs
  37. 20 23
      frameworks/CSharp/aspnetcore/Benchmarks/Controllers/FortunesController.cs
  38. 31 34
      frameworks/CSharp/aspnetcore/Benchmarks/Controllers/HomeController.cs
  39. 26 29
      frameworks/CSharp/aspnetcore/Benchmarks/Controllers/MultipleQueriesController.cs
  40. 26 29
      frameworks/CSharp/aspnetcore/Benchmarks/Controllers/MultipleUpdatesController.cs
  41. 25 28
      frameworks/CSharp/aspnetcore/Benchmarks/Controllers/SingleQueryController.cs
  42. 10 11
      frameworks/CSharp/aspnetcore/Benchmarks/Data/ApplicationDbContext.cs
  43. 26 30
      frameworks/CSharp/aspnetcore/Benchmarks/Data/BatchUpdateString.cs
  44. 70 76
      frameworks/CSharp/aspnetcore/Benchmarks/Data/DapperDb.cs
  45. 58 63
      frameworks/CSharp/aspnetcore/Benchmarks/Data/EfDb.cs
  46. 18 20
      frameworks/CSharp/aspnetcore/Benchmarks/Data/Fortune.cs
  47. 6 10
      frameworks/CSharp/aspnetcore/Benchmarks/Data/IDb.cs
  48. 4 5
      frameworks/CSharp/aspnetcore/Benchmarks/Data/IRandom.cs
  49. 17 20
      frameworks/CSharp/aspnetcore/Benchmarks/Data/Random.cs
  50. 111 127
      frameworks/CSharp/aspnetcore/Benchmarks/Data/RawDb.cs
  51. 36 38
      frameworks/CSharp/aspnetcore/Benchmarks/Data/StringBuilderCache.cs
  52. 8 9
      frameworks/CSharp/aspnetcore/Benchmarks/Data/World.cs
  53. 25 31
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/FortunesDapperMiddleware.cs
  54. 25 31
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/FortunesEfMiddleware.cs
  55. 25 31
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/FortunesRawMiddleware.cs
  56. 28 37
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/JsonMiddleware.cs
  57. 35 39
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MiddlewareHelpers.cs
  58. 29 35
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleQueriesDapperMiddleware.cs
  59. 29 35
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleQueriesEfMiddleware.cs
  60. 29 35
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleQueriesRawMiddleware.cs
  61. 29 35
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesDapperMiddleware.cs
  62. 29 35
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesEfMiddleware.cs
  63. 29 35
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesRawMiddleware.cs
  64. 29 34
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/PlaintextMiddleware.cs
  65. 28 34
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/SingleQueryDapperMiddleware.cs
  66. 28 34
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/SingleQueryEfMiddleware.cs
  67. 28 34
      frameworks/CSharp/aspnetcore/Benchmarks/Middleware/SingleQueryRawMiddleware.cs
  68. 45 54
      frameworks/CSharp/aspnetcore/Benchmarks/Program.cs
  69. 149 155
      frameworks/CSharp/aspnetcore/Benchmarks/Startup.cs
  70. 36 38
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/AsciiString.cs
  71. 5 6
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.Caching.cs
  72. 140 144
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.HttpConnection.cs
  73. 19 20
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.Json.cs
  74. 15 16
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.Plaintext.cs
  75. 103 104
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.cs
  76. 36 42
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkConfigurationHelpers.cs
  77. 44 45
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/BufferExtensions.cs
  78. 99 101
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/BufferWriter.cs
  79. 5 6
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Configuration/AppSettings.cs
  80. 7 8
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Configuration/DatabaseServer.cs
  81. 28 31
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/BatchUpdateString.cs
  82. 6 7
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/CachedWorld.cs
  83. 11 14
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/Fortune.cs
  84. 5 6
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/JsonMessage.cs
  85. 17 20
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/Random.cs
  86. 6 7
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/World.cs
  87. 43 45
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/DateHeader.cs
  88. 14 15
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/HttpApplication.cs
  89. 6 8
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/IHttpConnection.cs
  90. 3 2
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/PlatformBenchmarks.csproj
  91. 46 52
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Program.cs
  92. 3 7
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/Startup.cs
  93. 36 38
      frameworks/CSharp/aspnetcore/PlatformBenchmarks/StringBuilderCache.cs
  94. 2 2
      frameworks/CSharp/aspnetcore/aspcore-ado-my.dockerfile
  95. 2 2
      frameworks/CSharp/aspnetcore/aspcore-ado-pg-up.dockerfile
  96. 2 2
      frameworks/CSharp/aspnetcore/aspcore-ado-pg.dockerfile
  97. 2 2
      frameworks/CSharp/aspnetcore/aspcore-mvc-ado-my.dockerfile
  98. 2 2
      frameworks/CSharp/aspnetcore/aspcore-mvc-ado-pg-up.dockerfile
  99. 2 2
      frameworks/CSharp/aspnetcore/aspcore-mvc-ado-pg.dockerfile
  100. 2 2
      frameworks/CSharp/aspnetcore/aspcore-mvc-dap-my.dockerfile

+ 8 - 0
frameworks/CSharp/.editorconfig

@@ -0,0 +1,8 @@
+[*.cs]
+indent_style = space
+indent_size = 4
+
+[*.json]
+indent_size = 2
+
+csharp_style_namespace_declarations = file_scoped

+ 36 - 38
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/AsciiString.cs

@@ -1,59 +1,57 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public readonly struct AsciiString : IEquatable<AsciiString>
 {
-    public readonly struct AsciiString : IEquatable<AsciiString>
-    {
-        private readonly byte[] _data;
+    private readonly byte[] _data;
 
-        public AsciiString(string s) => _data = Encoding.ASCII.GetBytes(s);
+    public AsciiString(string s) => _data = Encoding.ASCII.GetBytes(s);
 
-        private AsciiString(byte[] b) => _data = b;
+    private AsciiString(byte[] b) => _data = b;
 
-        public int Length => _data.Length;
+    public int Length => _data.Length;
 
-        public ReadOnlySpan<byte> AsSpan() => _data;
+    public ReadOnlySpan<byte> AsSpan() => _data;
 
-        public static implicit operator ReadOnlySpan<byte>(AsciiString str) => str._data;
-        public static implicit operator byte[] (AsciiString str) => str._data;
+    public static implicit operator ReadOnlySpan<byte>(AsciiString str) => str._data;
+    public static implicit operator byte[](AsciiString str) => str._data;
 
-        public static implicit operator AsciiString(string str) => new AsciiString(str);
+    public static implicit operator AsciiString(string str) => new(str);
 
-        public override string ToString() => Encoding.ASCII.GetString(_data);
-        public static explicit operator string(AsciiString str) => str.ToString();
+    public override string ToString() => Encoding.ASCII.GetString(_data);
+    public static explicit operator string(AsciiString str) => str.ToString();
 
-        public bool Equals(AsciiString other) => ReferenceEquals(_data, other._data) || SequenceEqual(_data, other._data);
-        private bool SequenceEqual(byte[] data1, byte[] data2) => new Span<byte>(data1).SequenceEqual(data2);
+    public bool Equals(AsciiString other) => ReferenceEquals(_data, other._data) || SequenceEqual(_data, other._data);
+    private bool SequenceEqual(byte[] data1, byte[] data2) => new Span<byte>(data1).SequenceEqual(data2);
 
-        public static bool operator ==(AsciiString a, AsciiString b) => a.Equals(b);
-        public static bool operator !=(AsciiString a, AsciiString b) => !a.Equals(b);
-        public override bool Equals(object other) => (other is AsciiString) && Equals((AsciiString)other);
+    public static bool operator ==(AsciiString a, AsciiString b) => a.Equals(b);
+    public static bool operator !=(AsciiString a, AsciiString b) => !a.Equals(b);
+    public override bool Equals(object other) => (other is AsciiString @string) && Equals(@string);
 
-        public static AsciiString operator +(AsciiString a, AsciiString b)
-        {
-            var result = new byte[a.Length + b.Length];
-            a._data.CopyTo(result, 0);
-            b._data.CopyTo(result, a.Length);
-            return new AsciiString(result);
-        }
+    public static AsciiString operator +(AsciiString a, AsciiString b)
+    {
+        var result = new byte[a.Length + b.Length];
+        a._data.CopyTo(result, 0);
+        b._data.CopyTo(result, a.Length);
+        return new AsciiString(result);
+    }
 
-        public override int GetHashCode()
+    public override int GetHashCode()
+    {
+        // Copied from x64 version of string.GetLegacyNonRandomizedHashCode()
+        // https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/String.Comparison.cs
+        var data = _data;
+        int hash1 = 5381;
+        int hash2 = hash1;
+        foreach (int b in data)
         {
-            // Copied from x64 version of string.GetLegacyNonRandomizedHashCode()
-            // https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/String.Comparison.cs
-            var data = _data;
-            int hash1 = 5381;
-            int hash2 = hash1;
-            foreach (int b in data)
-            {
-                hash1 = ((hash1 << 5) + hash1) ^ b;
-            }
-            return hash1 + (hash2 * 1566083941);
+            hash1 = ((hash1 << 5) + hash1) ^ b;
         }
-
+        return hash1 + (hash2 * 1566083941);
     }
+
 }

+ 5 - 6
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.Caching.cs

@@ -6,14 +6,13 @@
 using System.IO.Pipelines;
 using System.Threading.Tasks;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication
 {
-    public partial class BenchmarkApplication
+    private async Task Caching(PipeWriter pipeWriter, int count)
     {
-        private async Task Caching(PipeWriter pipeWriter, int count)
-        {
-            OutputMultipleQueries(pipeWriter, await Db.LoadCachedQueries(count), SerializerContext.CachedWorldArray);
-        }
+        OutputMultipleQueries(pipeWriter, await Db.LoadCachedQueries(count), SerializerContext.CachedWorldArray);
     }
 }
 

+ 140 - 144
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.HttpConnection.cs

@@ -1,141 +1,138 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Buffers;
 using System.IO.Pipelines;
 using System.Runtime.CompilerServices;
 using System.Text.Encodings.Web;
 using System.Text.Unicode;
-using System.Threading;
-using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication : IHttpConnection
 {
-    public partial class BenchmarkApplication : IHttpConnection
-    {
-        private State _state;
+    private State _state;
 
-        public PipeReader Reader { get; set; }
-        public PipeWriter Writer { get; set; }
+    public PipeReader Reader { get; set; }
+    public PipeWriter Writer { get; set; }
 
-        protected HtmlEncoder HtmlEncoder { get; } = CreateHtmlEncoder();
+    protected HtmlEncoder HtmlEncoder { get; } = CreateHtmlEncoder();
 
-        private HttpParser<ParsingAdapter> Parser { get; } = new HttpParser<ParsingAdapter>();
+    private HttpParser<ParsingAdapter> Parser { get; } = new HttpParser<ParsingAdapter>();
 
-        public async Task ExecuteAsync()
+    public async Task ExecuteAsync()
+    {
+        try
         {
-            try
-            {
-                await ProcessRequestsAsync();
+            await ProcessRequestsAsync();
 
-                Reader.Complete();
-            }
-            catch (Exception ex)
-            {
-                Reader.Complete(ex);
-            }
-            finally
-            {
-                Writer.Complete();
-            }
+            Reader.Complete();
         }
-
-        private static HtmlEncoder CreateHtmlEncoder()
+        catch (Exception ex)
+        {
+            Reader.Complete(ex);
+        }
+        finally
         {
-            var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
-            settings.AllowCharacter('\u2014');  // allow EM DASH through
-            return HtmlEncoder.Create(settings);
+            Writer.Complete();
         }
+    }
+
+    private static HtmlEncoder CreateHtmlEncoder()
+    {
+        var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
+        settings.AllowCharacter('\u2014');  // allow EM DASH through
+        return HtmlEncoder.Create(settings);
+    }
 
 #if !DATABASE
-        private async Task ProcessRequestsAsync()
+    private async Task ProcessRequestsAsync()
+    {
+        while (true)
         {
-            while (true)
-            {
-                var readResult = await Reader.ReadAsync(default);
-                var buffer = readResult.Buffer;
-                var isCompleted = readResult.IsCompleted;
+            var readResult = await Reader.ReadAsync(default);
+            var buffer = readResult.Buffer;
+            var isCompleted = readResult.IsCompleted;
 
-                if (buffer.IsEmpty && isCompleted)
-                {
-                    return;
-                }
-
-                if (!HandleRequests(buffer, isCompleted))
-                {
-                    return;
-                }
+            if (buffer.IsEmpty && isCompleted)
+            {
+                return;
+            }
 
-                await Writer.FlushAsync(default);
+            if (!HandleRequests(buffer, isCompleted))
+            {
+                return;
             }
+
+            await Writer.FlushAsync(default);
         }
+    }
 
-        private bool HandleRequests(in ReadOnlySequence<byte> buffer, bool isCompleted)
-        {
-            var reader = new SequenceReader<byte>(buffer);
-            var writer = GetWriter(Writer, sizeHint: 160 * 16); // 160*16 is for Plaintext, for Json 160 would be enough
+    private bool HandleRequests(in ReadOnlySequence<byte> buffer, bool isCompleted)
+    {
+        var reader = new SequenceReader<byte>(buffer);
+        var writer = GetWriter(Writer, sizeHint: 160 * 16); // 160*16 is for Plaintext, for Json 160 would be enough
 
-            while (true)
+        while (true)
+        {
+            if (!ParseHttpRequest(ref reader, isCompleted))
             {
-                if (!ParseHttpRequest(ref reader, isCompleted))
-                {
-                    return false;
-                }
+                return false;
+            }
 
-                if (_state == State.Body)
-                {
-                    ProcessRequest(ref writer);
+            if (_state == State.Body)
+            {
+                ProcessRequest(ref writer);
 
-                    _state = State.StartLine;
+                _state = State.StartLine;
 
-                    if (!reader.End)
-                    {
-                        // More input data to parse
-                        continue;
-                    }
+                if (!reader.End)
+                {
+                    // More input data to parse
+                    continue;
                 }
-
-                // No more input or incomplete data, Advance the Reader
-                Reader.AdvanceTo(reader.Position, buffer.End);
-                break;
             }
 
-            writer.Commit();
-            return true;
+            // No more input or incomplete data, Advance the Reader
+            Reader.AdvanceTo(reader.Position, buffer.End);
+            break;
         }
 
-        private bool ParseHttpRequest(ref SequenceReader<byte> reader, bool isCompleted)
-        {
-            var state = _state;
+        writer.Commit();
+        return true;
+    }
 
-            if (state == State.StartLine)
-            {
-                if (Parser.ParseRequestLine(new ParsingAdapter(this), ref reader))
-                {
-                    state = State.Headers;
-                }
-            }
+    private bool ParseHttpRequest(ref SequenceReader<byte> reader, bool isCompleted)
+    {
+        var state = _state;
 
-            if (state == State.Headers)
+        if (state == State.StartLine)
+        {
+            if (Parser.ParseRequestLine(new ParsingAdapter(this), ref reader))
             {
-                var success = Parser.ParseHeaders(new ParsingAdapter(this), ref reader);
-
-                if (success)
-                {
-                    state = State.Body;
-                }
+                state = State.Headers;
             }
+        }
 
-            if (state != State.Body && isCompleted)
+        if (state == State.Headers)
+        {
+            var success = Parser.ParseHeaders(new ParsingAdapter(this), ref reader);
+
+            if (success)
             {
-                ThrowUnexpectedEndOfData();
+                state = State.Body;
             }
+        }
 
-            _state = state;
-            return true;
+        if (state != State.Body && isCompleted)
+        {
+            ThrowUnexpectedEndOfData();
         }
+
+        _state = state;
+        return true;
+    }
 #else
         private async Task ProcessRequestsAsync()
         {
@@ -224,76 +221,75 @@ namespace PlatformBenchmarks
         }
 #endif
 
-        public void OnStaticIndexedHeader(int index)
-        {
-        }
+    public void OnStaticIndexedHeader(int index)
+    {
+    }
 
-        public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
-        {
-        }
+    public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
+    {
+    }
 
-        public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
-        {
-        }
+    public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
+    {
+    }
 
-        public void OnHeadersComplete(bool endStream)
-        {
-        }
+    public void OnHeadersComplete(bool endStream)
+    {
+    }
 
-        private static void ThrowUnexpectedEndOfData()
-        {
-            throw new InvalidOperationException("Unexpected end of data!");
-        }
+    private static void ThrowUnexpectedEndOfData()
+    {
+        throw new InvalidOperationException("Unexpected end of data!");
+    }
 
-        private enum State
-        {
-            StartLine,
-            Headers,
-            Body
-        }
+    private enum State
+    {
+        StartLine,
+        Headers,
+        Body
+    }
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private static BufferWriter<WriterAdapter> GetWriter(PipeWriter pipeWriter, int sizeHint)
-            => new BufferWriter<WriterAdapter>(new WriterAdapter(pipeWriter), sizeHint);
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    private static BufferWriter<WriterAdapter> GetWriter(PipeWriter pipeWriter, int sizeHint)
+        => new(new WriterAdapter(pipeWriter), sizeHint);
 
-        private struct WriterAdapter : IBufferWriter<byte>
-        {
-            public PipeWriter Writer;
+    private struct WriterAdapter : IBufferWriter<byte>
+    {
+        public PipeWriter Writer;
 
-            public WriterAdapter(PipeWriter writer)
-                => Writer = writer;
+        public WriterAdapter(PipeWriter writer)
+            => Writer = writer;
 
-            public void Advance(int count)
-                => Writer.Advance(count);
+        public void Advance(int count)
+            => Writer.Advance(count);
 
-            public Memory<byte> GetMemory(int sizeHint = 0)
-                => Writer.GetMemory(sizeHint);
+        public Memory<byte> GetMemory(int sizeHint = 0)
+            => Writer.GetMemory(sizeHint);
 
-            public Span<byte> GetSpan(int sizeHint = 0)
-                => Writer.GetSpan(sizeHint);
-        }
+        public Span<byte> GetSpan(int sizeHint = 0)
+            => Writer.GetSpan(sizeHint);
+    }
 
-        private struct ParsingAdapter : IHttpRequestLineHandler, IHttpHeadersHandler
-        {
-            public BenchmarkApplication RequestHandler;
+    private struct ParsingAdapter : IHttpRequestLineHandler, IHttpHeadersHandler
+    {
+        public BenchmarkApplication RequestHandler;
 
-            public ParsingAdapter(BenchmarkApplication requestHandler)
-                => RequestHandler = requestHandler;
+        public ParsingAdapter(BenchmarkApplication requestHandler)
+            => RequestHandler = requestHandler;
 
-            public void OnStaticIndexedHeader(int index) 
-                => RequestHandler.OnStaticIndexedHeader(index);
+        public void OnStaticIndexedHeader(int index)
+            => RequestHandler.OnStaticIndexedHeader(index);
 
-            public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
-                => RequestHandler.OnStaticIndexedHeader(index, value);
+        public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
+            => RequestHandler.OnStaticIndexedHeader(index, value);
 
-            public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
-                => RequestHandler.OnHeader(name, value);
+        public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
+            => RequestHandler.OnHeader(name, value);
 
-            public void OnHeadersComplete(bool endStream)
-                => RequestHandler.OnHeadersComplete(endStream);
+        public void OnHeadersComplete(bool endStream)
+            => RequestHandler.OnHeadersComplete(endStream);
 
-            public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
-                => RequestHandler.OnStartLine(versionAndMethod, targetPath, startLine);
-        }
+        public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
+            => RequestHandler.OnStartLine(versionAndMethod, targetPath, startLine);
     }
 }

+ 19 - 20
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.Json.cs

@@ -4,32 +4,31 @@
 using System.Buffers;
 using System.Text.Json;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication
 {
-    public partial class BenchmarkApplication
-    {
-        private readonly static uint _jsonPayloadSize = (uint)JsonSerializer.SerializeToUtf8Bytes(new JsonMessage { message = "Hello, World!" }, SerializerContext.JsonMessage).Length;
+    private readonly static uint _jsonPayloadSize = (uint)JsonSerializer.SerializeToUtf8Bytes(new JsonMessage { message = "Hello, World!" }, SerializerContext.JsonMessage).Length;
 
-        private readonly static AsciiString _jsonPreamble =
-            _http11OK +
-            _headerServer + _crlf +
-            _headerContentTypeJson + _crlf +
-            _headerContentLength + _jsonPayloadSize.ToString();
+    private readonly static AsciiString _jsonPreamble =
+        _http11OK +
+        _headerServer + _crlf +
+        _headerContentTypeJson + _crlf +
+        _headerContentLength + _jsonPayloadSize.ToString();
 
-        private static void Json(ref BufferWriter<WriterAdapter> writer, IBufferWriter<byte> bodyWriter)
-        {
-            writer.Write(_jsonPreamble);
+    private static void Json(ref BufferWriter<WriterAdapter> writer, IBufferWriter<byte> bodyWriter)
+    {
+        writer.Write(_jsonPreamble);
 
-            // Date header
-            writer.Write(DateHeader.HeaderBytes);
+        // Date header
+        writer.Write(DateHeader.HeaderBytes);
 
-            writer.Commit();
+        writer.Commit();
 
-            Utf8JsonWriter utf8JsonWriter = t_writer ??= new Utf8JsonWriter(bodyWriter, new JsonWriterOptions { SkipValidation = true });
-            utf8JsonWriter.Reset(bodyWriter);
+        Utf8JsonWriter utf8JsonWriter = t_writer ??= new Utf8JsonWriter(bodyWriter, new JsonWriterOptions { SkipValidation = true });
+        utf8JsonWriter.Reset(bodyWriter);
 
-            // Body
-            JsonSerializer.Serialize(utf8JsonWriter, new JsonMessage { message = "Hello, World!" }, SerializerContext.JsonMessage);        
-        }
+        // Body
+        JsonSerializer.Serialize(utf8JsonWriter, new JsonMessage { message = "Hello, World!" }, SerializerContext.JsonMessage);
     }
 }

+ 15 - 16
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.Plaintext.cs

@@ -1,25 +1,24 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication
 {
-    public partial class BenchmarkApplication
-    {
-        private readonly static AsciiString _plaintextPreamble =
-            _http11OK +
-            _headerServer + _crlf +
-            _headerContentTypeText + _crlf +
-            _headerContentLength + _plainTextBody.Length.ToString();
+    private readonly static AsciiString _plaintextPreamble =
+        _http11OK +
+        _headerServer + _crlf +
+        _headerContentTypeText + _crlf +
+        _headerContentLength + _plainTextBody.Length.ToString();
 
-        private static void PlainText(ref BufferWriter<WriterAdapter> writer)
-        {
-            writer.Write(_plaintextPreamble);
+    private static void PlainText(ref BufferWriter<WriterAdapter> writer)
+    {
+        writer.Write(_plaintextPreamble);
 
-            // Date header
-            writer.Write(DateHeader.HeaderBytes);
+        // Date header
+        writer.Write(DateHeader.HeaderBytes);
 
-            // Body
-            writer.Write(_plainTextBody);
-        }
+        // Body
+        writer.Write(_plainTextBody);
     }
 }

+ 103 - 104
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkApplication.cs

@@ -10,86 +10,86 @@ using System.Threading.Tasks;
 
 using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication
 {
-    public partial class BenchmarkApplication
+    private readonly static AsciiString _applicationName = "Kestrel Platform-Level Application";
+    public static AsciiString ApplicationName => _applicationName;
+
+    private readonly static AsciiString _crlf = "\r\n";
+    private readonly static AsciiString _eoh = "\r\n\r\n"; // End Of Headers
+    private readonly static AsciiString _http11OK = "HTTP/1.1 200 OK\r\n";
+    private readonly static AsciiString _http11NotFound = "HTTP/1.1 404 Not Found\r\n";
+    private readonly static AsciiString _headerServer = "Server: K";
+    private readonly static AsciiString _headerContentLength = "Content-Length: ";
+    private readonly static AsciiString _headerContentLengthZero = "Content-Length: 0";
+    private readonly static AsciiString _headerContentTypeText = "Content-Type: text/plain";
+    private readonly static AsciiString _headerContentTypeJson = "Content-Type: application/json";
+    private readonly static AsciiString _headerContentTypeHtml = "Content-Type: text/html; charset=UTF-8";
+
+    private readonly static AsciiString _dbPreamble =
+        _http11OK +
+        _headerServer + _crlf +
+        _headerContentTypeJson + _crlf +
+        _headerContentLength;
+
+    private readonly static AsciiString _plainTextBody = "Hello, World!";
+
+    private static readonly JsonContext SerializerContext = JsonContext.Default;
+
+    [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Serialization, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
+    [JsonSerializable(typeof(JsonMessage))]
+    [JsonSerializable(typeof(CachedWorld[]))]
+    [JsonSerializable(typeof(World[]))]
+    private sealed partial class JsonContext : JsonSerializerContext
     {
-        private readonly static AsciiString _applicationName = "Kestrel Platform-Level Application";
-        public static AsciiString ApplicationName => _applicationName;
-
-        private readonly static AsciiString _crlf = "\r\n";
-        private readonly static AsciiString _eoh = "\r\n\r\n"; // End Of Headers
-        private readonly static AsciiString _http11OK = "HTTP/1.1 200 OK\r\n";
-        private readonly static AsciiString _http11NotFound = "HTTP/1.1 404 Not Found\r\n";
-        private readonly static AsciiString _headerServer = "Server: K";
-        private readonly static AsciiString _headerContentLength = "Content-Length: ";
-        private readonly static AsciiString _headerContentLengthZero = "Content-Length: 0";
-        private readonly static AsciiString _headerContentTypeText = "Content-Type: text/plain";
-        private readonly static AsciiString _headerContentTypeJson = "Content-Type: application/json";
-        private readonly static AsciiString _headerContentTypeHtml = "Content-Type: text/html; charset=UTF-8";
-
-        private readonly static AsciiString _dbPreamble =
-            _http11OK +
-            _headerServer + _crlf +
-            _headerContentTypeJson + _crlf +
-            _headerContentLength;
-
-        private readonly static AsciiString _plainTextBody = "Hello, World!";
-
-        private static readonly JsonContext SerializerContext = JsonContext.Default;
-
-        [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Serialization, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
-        [JsonSerializable(typeof(JsonMessage))]
-        [JsonSerializable(typeof(CachedWorld[]))]
-        [JsonSerializable(typeof(World[]))]
-        private sealed partial class JsonContext : JsonSerializerContext
-        {
-        }
+    }
 
-        private readonly static AsciiString _fortunesTableStart = "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>";
-        private readonly static AsciiString _fortunesRowStart = "<tr><td>";
-        private readonly static AsciiString _fortunesColumn = "</td><td>";
-        private readonly static AsciiString _fortunesRowEnd = "</td></tr>";
-        private readonly static AsciiString _fortunesTableEnd = "</table></body></html>";
-        private readonly static AsciiString _contentLengthGap = new string(' ', 4);
+    private readonly static AsciiString _fortunesTableStart = "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>";
+    private readonly static AsciiString _fortunesRowStart = "<tr><td>";
+    private readonly static AsciiString _fortunesColumn = "</td><td>";
+    private readonly static AsciiString _fortunesRowEnd = "</td></tr>";
+    private readonly static AsciiString _fortunesTableEnd = "</table></body></html>";
+    private readonly static AsciiString _contentLengthGap = new string(' ', 4);
 
 #if DATABASE
         public static RawDb Db { get; set; }
 #endif
 
-        [ThreadStatic]
-        private static Utf8JsonWriter t_writer;
+    [ThreadStatic]
+    private static Utf8JsonWriter t_writer;
 
-        public static class Paths
-        {
-            public readonly static AsciiString Json = "/json";
-            public readonly static AsciiString Plaintext = "/plaintext";
-            public readonly static AsciiString SingleQuery = "/db";
-            public readonly static AsciiString Fortunes = "/fortunes";
-            public readonly static AsciiString Updates = "/updates/";
-            public readonly static AsciiString MultipleQueries = "/queries/";
-            public readonly static AsciiString Caching = "/cached-worlds/";
-        }
+    public static class Paths
+    {
+        public readonly static AsciiString Json = "/json";
+        public readonly static AsciiString Plaintext = "/plaintext";
+        public readonly static AsciiString SingleQuery = "/db";
+        public readonly static AsciiString Fortunes = "/fortunes";
+        public readonly static AsciiString Updates = "/updates/";
+        public readonly static AsciiString MultipleQueries = "/queries/";
+        public readonly static AsciiString Caching = "/cached-worlds/";
+    }
+
+    private RequestType _requestType;
+    private int _queries;
 
-        private RequestType _requestType;
-        private int _queries;
+    public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
+    {
+        _requestType = versionAndMethod.Method == Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpMethod.Get ? GetRequestType(startLine.Slice(targetPath.Offset, targetPath.Length), ref _queries) : RequestType.NotRecognized;
+    }
 
-        public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
+    private RequestType GetRequestType(ReadOnlySpan<byte> path, ref int queries)
+    {
+#if !DATABASE
+        if (path.Length == 10 && path.SequenceEqual(Paths.Plaintext))
         {
-            _requestType = versionAndMethod.Method == HttpMethod.Get ? GetRequestType(startLine.Slice(targetPath.Offset, targetPath.Length), ref _queries) : RequestType.NotRecognized;
+            return RequestType.PlainText;
         }
-
-        private RequestType GetRequestType(ReadOnlySpan<byte> path, ref int queries)
+        else if (path.Length == 5 && path.SequenceEqual(Paths.Json))
         {
-#if !DATABASE
-            if (path.Length == 10 && path.SequenceEqual(Paths.Plaintext))
-            {
-                return RequestType.PlainText;
-            }
-            else if (path.Length == 5 && path.SequenceEqual(Paths.Json))
-            {
-                return RequestType.Json;
-            }
+            return RequestType.Json;
+        }
 #else
             if (path.Length == 3 && path[0] == '/' && path[1] == 'd' && path[2] == 'b')
             {
@@ -115,26 +115,26 @@ namespace PlatformBenchmarks
                 return RequestType.MultipleQueries;
             }
 #endif
-            return RequestType.NotRecognized;
-        }
+        return RequestType.NotRecognized;
+    }
 
 
 #if !DATABASE
-        private void ProcessRequest(ref BufferWriter<WriterAdapter> writer)
+    private void ProcessRequest(ref BufferWriter<WriterAdapter> writer)
+    {
+        if (_requestType == RequestType.PlainText)
         {
-            if (_requestType == RequestType.PlainText)
-            {
-                PlainText(ref writer);
-            }
-            else if (_requestType == RequestType.Json)
-            {
-                Json(ref writer, Writer);
-            }
-            else
-            {
-                Default(ref writer);
-            }
+            PlainText(ref writer);
         }
+        else if (_requestType == RequestType.Json)
+        {
+            Json(ref writer, Writer);
+        }
+        else
+        {
+            Default(ref writer);
+        }
+    }
 #else
 
         private static int ParseQueries(ReadOnlySpan<byte> parameter)
@@ -169,30 +169,29 @@ namespace PlatformBenchmarks
             return Task.CompletedTask;
         }
 #endif
-        private readonly static AsciiString _defaultPreamble =
-            _http11NotFound +
-            _headerServer + _crlf +
-            _headerContentTypeText + _crlf +
-            _headerContentLengthZero;
+    private readonly static AsciiString _defaultPreamble =
+        _http11NotFound +
+        _headerServer + _crlf +
+        _headerContentTypeText + _crlf +
+        _headerContentLengthZero;
 
-        private static void Default(ref BufferWriter<WriterAdapter> writer)
-        {
-            writer.Write(_defaultPreamble);
+    private static void Default(ref BufferWriter<WriterAdapter> writer)
+    {
+        writer.Write(_defaultPreamble);
 
-            // Date header
-            writer.Write(DateHeader.HeaderBytes);
-        }
+        // Date header
+        writer.Write(DateHeader.HeaderBytes);
+    }
 
-        private enum RequestType
-        {
-            NotRecognized,
-            PlainText,
-            Json,
-            Fortunes,
-            SingleQuery,
-            Caching,
-            Updates,
-            MultipleQueries
-        }
+    private enum RequestType
+    {
+        NotRecognized,
+        PlainText,
+        Json,
+        Fortunes,
+        SingleQuery,
+        Caching,
+        Updates,
+        MultipleQueries
     }
-}
+}

+ 36 - 42
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BenchmarkConfigurationHelpers.cs

@@ -1,64 +1,58 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Net;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Configuration;
-using System.IO.Pipelines;
 using System.Runtime.InteropServices;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public static class BenchmarkConfigurationHelpers
 {
-    public static class BenchmarkConfigurationHelpers
+    public static IWebHostBuilder UseBenchmarksConfiguration(this IWebHostBuilder builder, IConfiguration configuration)
     {
-        public static IWebHostBuilder UseBenchmarksConfiguration(this IWebHostBuilder builder, IConfiguration configuration)
+        builder.UseConfiguration(configuration);
+
+        builder.UseSockets(options =>
         {
-            builder.UseConfiguration(configuration);
+            if (int.TryParse(builder.GetSetting("threadCount"), out int threadCount))
+            {
+                options.IOQueueCount = threadCount;
+            }
 
-            builder.UseSockets(options =>
+            options.WaitForDataBeforeAllocatingBuffer = false;
+            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
             {
-                if (int.TryParse(builder.GetSetting("threadCount"), out int threadCount))
-                {
-                    options.IOQueueCount = threadCount;
-                }
+                options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
+            }
 
-                options.WaitForDataBeforeAllocatingBuffer = false;
-                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
-                {
-                    options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
-                }
+            Console.WriteLine($"Options: WaitForData={options.WaitForDataBeforeAllocatingBuffer}, PreferInlineScheduling={options.UnsafePreferInlineScheduling}, IOQueue={options.IOQueueCount}");
+        });
 
-                Console.WriteLine($"Options: WaitForData={options.WaitForDataBeforeAllocatingBuffer}, PreferInlineScheduling={options.UnsafePreferInlineScheduling}, IOQueue={options.IOQueueCount}");
-            });
+        return builder;
+    }
 
-            return builder;
-        }
+    public static IPEndPoint CreateIPEndPoint(this IConfiguration config)
+    {
+        var url = config["server.urls"] ?? config["urls"];
 
-        public static IPEndPoint CreateIPEndPoint(this IConfiguration config)
+        if (string.IsNullOrEmpty(url))
         {
-            var url = config["server.urls"] ?? config["urls"];
-
-            if (string.IsNullOrEmpty(url))
-            {
-                return new IPEndPoint(IPAddress.Loopback, 8080);
-            }
-
-            var address = BindingAddress.Parse(url);
+            return new IPEndPoint(IPAddress.Loopback, 8080);
+        }
 
-            IPAddress ip;
+        var address = BindingAddress.Parse(url);
 
-            if (string.Equals(address.Host, "localhost", StringComparison.OrdinalIgnoreCase))
-            {
-                ip = IPAddress.Loopback;
-            }
-            else if (!IPAddress.TryParse(address.Host, out ip))
-            {
-                ip = IPAddress.IPv6Any;
-            }
+        IPAddress ip;
 
-            return new IPEndPoint(ip, address.Port);
+        if (string.Equals(address.Host, "localhost", StringComparison.OrdinalIgnoreCase))
+        {
+            ip = IPAddress.Loopback;
         }
+        else if (!IPAddress.TryParse(address.Host, out ip))
+        {
+            ip = IPAddress.IPv6Any;
+        }
+
+        return new IPEndPoint(ip, address.Port);
     }
 }

+ 44 - 45
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BufferExtensions.cs

@@ -6,58 +6,57 @@ using System.Buffers;
 using System.Runtime.CompilerServices;
 using System.Text;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+// Same as KestrelHttpServer\src\Kestrel.Core\Internal\Http\PipelineExtensions.cs
+// However methods accept T : struct, IBufferWriter<byte> rather than PipeWriter.
+// This allows a struct wrapper to turn CountingBufferWriter into a non-shared generic,
+// while still offering the WriteNumeric extension.
+
+public static class BufferExtensions
 {
-    // Same as KestrelHttpServer\src\Kestrel.Core\Internal\Http\PipelineExtensions.cs
-    // However methods accept T : struct, IBufferWriter<byte> rather than PipeWriter.
-    // This allows a struct wrapper to turn CountingBufferWriter into a non-shared generic,
-    // while still offering the WriteNumeric extension.
+    private const int _maxULongByteLength = 20;
 
-    public static class BufferExtensions
-    {
-        private const int _maxULongByteLength = 20;
+    [ThreadStatic]
+    private static byte[] _numericBytesScratch;
 
-        [ThreadStatic]
-        private static byte[] _numericBytesScratch;
+    internal static void WriteUtf8String<T>(ref this BufferWriter<T> buffer, string text)
+         where T : struct, IBufferWriter<byte>
+    {
+        var byteCount = Encoding.UTF8.GetByteCount(text);
+        buffer.Ensure(byteCount);
+        byteCount = Encoding.UTF8.GetBytes(text.AsSpan(), buffer.Span);
+        buffer.Advance(byteCount);
+    }
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    internal static void WriteNumericMultiWrite<T>(ref this BufferWriter<T> buffer, uint number)
+         where T : IBufferWriter<byte>
+    {
+        const byte AsciiDigitStart = (byte)'0';
 
-        internal static void WriteUtf8String<T>(ref this BufferWriter<T> buffer, string text)
-             where T : struct, IBufferWriter<byte>
+        var value = number;
+        var position = _maxULongByteLength;
+        var byteBuffer = NumericBytesScratch;
+        do
         {
-            var byteCount = Encoding.UTF8.GetByteCount(text);
-            buffer.Ensure(byteCount);
-            byteCount = Encoding.UTF8.GetBytes(text.AsSpan(), buffer.Span);
-            buffer.Advance(byteCount);
-        }
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        internal static void WriteNumericMultiWrite<T>(ref this BufferWriter<T> buffer, uint number)
-             where T : IBufferWriter<byte>
-        {
-            const byte AsciiDigitStart = (byte)'0';
-
-            var value = number;
-            var position = _maxULongByteLength;
-            var byteBuffer = NumericBytesScratch;
-            do
-            {
-                // Consider using Math.DivRem() if available
-                var quotient = value / 10;
-                byteBuffer[--position] = (byte)(AsciiDigitStart + (value - quotient * 10)); // 0x30 = '0'
-                value = quotient;
-            }
-            while (value != 0);
-
-            var length = _maxULongByteLength - position;
-            buffer.Write(new ReadOnlySpan<byte>(byteBuffer, position, length));
+            // Consider using Math.DivRem() if available
+            var quotient = value / 10;
+            byteBuffer[--position] = (byte)(AsciiDigitStart + (value - quotient * 10)); // 0x30 = '0'
+            value = quotient;
         }
+        while (value != 0);
 
-        private static byte[] NumericBytesScratch => _numericBytesScratch ?? CreateNumericBytesScratch();
+        var length = _maxULongByteLength - position;
+        buffer.Write(new ReadOnlySpan<byte>(byteBuffer, position, length));
+    }
 
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static byte[] CreateNumericBytesScratch()
-        {
-            var bytes = new byte[_maxULongByteLength];
-            _numericBytesScratch = bytes;
-            return bytes;
-        }
+    private static byte[] NumericBytesScratch => _numericBytesScratch ?? CreateNumericBytesScratch();
+
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    private static byte[] CreateNumericBytesScratch()
+    {
+        var bytes = new byte[_maxULongByteLength];
+        _numericBytesScratch = bytes;
+        return bytes;
     }
 }

+ 99 - 101
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/BufferWriter.cs

@@ -1,143 +1,141 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Buffers;
 using System.Runtime.CompilerServices;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public ref struct BufferWriter<T> where T : IBufferWriter<byte>
 {
-    public ref struct BufferWriter<T> where T : IBufferWriter<byte>
-    {
-        private T _output;
-        private Span<byte> _span;
-        private int _buffered;
+    private readonly T _output;
+    private Span<byte> _span;
+    private int _buffered;
 
-        public BufferWriter(T output, int sizeHint)
-        {
-            _buffered = 0;
-            _output = output;
-            _span = output.GetSpan(sizeHint);
-        }
+    public BufferWriter(T output, int sizeHint)
+    {
+        _buffered = 0;
+        _output = output;
+        _span = output.GetSpan(sizeHint);
+    }
 
-        public Span<byte> Span => _span;
+    public Span<byte> Span => _span;
 
-        public T Output => _output;
+    public T Output => _output;
 
-        public int Buffered => _buffered;
+    public int Buffered => _buffered;
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Commit()
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Commit()
+    {
+        var buffered = _buffered;
+        if (buffered > 0)
         {
-            var buffered = _buffered;
-            if (buffered > 0)
-            {
-                _buffered = 0;
-                _output.Advance(buffered);
-            }
+            _buffered = 0;
+            _output.Advance(buffered);
         }
+    }
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Advance(int count)
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Advance(int count)
+    {
+        _buffered += count;
+        _span = _span.Slice(count);
+    }
+
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Write(ReadOnlySpan<byte> source)
+    {
+        if (_span.Length >= source.Length)
         {
-            _buffered += count;
-            _span = _span.Slice(count);
+            source.CopyTo(_span);
+            Advance(source.Length);
         }
-
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Write(ReadOnlySpan<byte> source)
+        else
         {
-            if (_span.Length >= source.Length)
-            {
-                source.CopyTo(_span);
-                Advance(source.Length);
-            }
-            else
-            {
-                WriteMultiBuffer(source);
-            }
+            WriteMultiBuffer(source);
         }
+    }
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Ensure(int count = 1)
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Ensure(int count = 1)
+    {
+        if (_span.Length < count)
         {
-            if (_span.Length < count)
-            {
-                EnsureMore(count);
-            }
+            EnsureMore(count);
         }
+    }
 
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private void EnsureMore(int count = 0)
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    private void EnsureMore(int count = 0)
+    {
+        if (_buffered > 0)
         {
-            if (_buffered > 0)
-            {
-                Commit();
-            }
-
-            _span = _output.GetSpan(count);
+            Commit();
         }
 
-        private void WriteMultiBuffer(ReadOnlySpan<byte> source)
+        _span = _output.GetSpan(count);
+    }
+
+    private void WriteMultiBuffer(ReadOnlySpan<byte> source)
+    {
+        while (source.Length > 0)
         {
-            while (source.Length > 0)
+            if (_span.Length == 0)
             {
-                if (_span.Length == 0)
-                {
-                    EnsureMore();
-                }
-
-                var writable = Math.Min(source.Length, _span.Length);
-                source.Slice(0, writable).CopyTo(_span);
-                source = source.Slice(writable);
-                Advance(writable);
+                EnsureMore();
             }
+
+            var writable = Math.Min(source.Length, _span.Length);
+            source[..writable].CopyTo(_span);
+            source = source[writable..];
+            Advance(writable);
         }
+    }
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        internal void WriteNumeric(uint number)
-        {
-            const byte AsciiDigitStart = (byte)'0';
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    internal void WriteNumeric(uint number)
+    {
+        const byte AsciiDigitStart = (byte)'0';
 
-            var span = this.Span;
+        var span = this.Span;
 
-            // Fast path, try copying to the available memory directly
-            var advanceBy = 0;
-            if (span.Length >= 3)
+        // Fast path, try copying to the available memory directly
+        var advanceBy = 0;
+        if (span.Length >= 3)
+        {
+            if (number < 10)
             {
-                if (number < 10)
-                {
-                    span[0] = (byte)(number + AsciiDigitStart);
-                    advanceBy = 1;
-                }
-                else if (number < 100)
-                {
-                    var tens = (byte)((number * 205u) >> 11); // div10, valid to 1028
-
-                    span[0] = (byte)(tens + AsciiDigitStart);
-                    span[1] = (byte)(number - (tens * 10) + AsciiDigitStart);
-                    advanceBy = 2;
-                }
-                else if (number < 1000)
-                {
-                    var digit0 = (byte)((number * 41u) >> 12); // div100, valid to 1098
-                    var digits01 = (byte)((number * 205u) >> 11); // div10, valid to 1028
-
-                    span[0] = (byte)(digit0 + AsciiDigitStart);
-                    span[1] = (byte)(digits01 - (digit0 * 10) + AsciiDigitStart);
-                    span[2] = (byte)(number - (digits01 * 10) + AsciiDigitStart);
-                    advanceBy = 3;
-                }
+                span[0] = (byte)(number + AsciiDigitStart);
+                advanceBy = 1;
             }
-
-            if (advanceBy > 0)
+            else if (number < 100)
             {
-                Advance(advanceBy);
+                var tens = (byte)((number * 205u) >> 11); // div10, valid to 1028
+
+                span[0] = (byte)(tens + AsciiDigitStart);
+                span[1] = (byte)(number - (tens * 10) + AsciiDigitStart);
+                advanceBy = 2;
             }
-            else
+            else if (number < 1000)
             {
-                BufferExtensions.WriteNumericMultiWrite(ref this, number);
+                var digit0 = (byte)((number * 41u) >> 12); // div100, valid to 1098
+                var digits01 = (byte)((number * 205u) >> 11); // div10, valid to 1028
+
+                span[0] = (byte)(digit0 + AsciiDigitStart);
+                span[1] = (byte)(digits01 - (digit0 * 10) + AsciiDigitStart);
+                span[2] = (byte)(number - (digits01 * 10) + AsciiDigitStart);
+                advanceBy = 3;
             }
         }
+
+        if (advanceBy > 0)
+        {
+            Advance(advanceBy);
+        }
+        else
+        {
+            BufferExtensions.WriteNumericMultiWrite(ref this, number);
+        }
     }
 }

+ 5 - 6
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Configuration/AppSettings.cs

@@ -1,12 +1,11 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public class AppSettings
 {
-    public class AppSettings
-    {
-        public string ConnectionString { get; set; }
+    public string ConnectionString { get; set; }
 
-        public DatabaseServer Database { get; set; } = DatabaseServer.None;
-    }
+    public DatabaseServer Database { get; set; } = DatabaseServer.None;
 }

+ 7 - 8
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Configuration/DatabaseServer.cs

@@ -1,13 +1,12 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public enum DatabaseServer
 {
-    public enum DatabaseServer
-    {
-        None,
-        SqlServer,
-        PostgreSql,
-        MySql
-    }
+    None,
+    SqlServer,
+    PostgreSql,
+    MySql
 }

+ 28 - 31
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/BatchUpdateString.cs

@@ -1,44 +1,41 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System.Linq;
+namespace PlatformBenchmarks;
 
-namespace PlatformBenchmarks
+internal class BatchUpdateString
 {
-    internal class BatchUpdateString
-    {
-        private const int MaxBatch = 500;
+    private const int MaxBatch = 500;
+
+    public static DatabaseServer DatabaseServer;
+
+    internal static readonly string[] Ids = Enumerable.Range(0, MaxBatch).Select(i => $"@Id_{i}").ToArray();
+    internal static readonly string[] Randoms = Enumerable.Range(0, MaxBatch).Select(i => $"@Random_{i}").ToArray();
 
-        public static DatabaseServer DatabaseServer;
+    private static readonly string[] _queries = new string[MaxBatch + 1];
+
+    public static string Query(int batchSize)
+    {
+        if (_queries[batchSize] != null)
+        {
+            return _queries[batchSize];
+        }
 
-        internal static readonly string[] Ids = Enumerable.Range(0, MaxBatch).Select(i => $"@Id_{i}").ToArray();
-        internal static readonly string[] Randoms = Enumerable.Range(0, MaxBatch).Select(i => $"@Random_{i}").ToArray();
+        var lastIndex = batchSize - 1;
 
-        private static string[] _queries = new string[MaxBatch + 1];
+        var sb = StringBuilderCache.Acquire();
 
-        public static string Query(int batchSize)
+        if (DatabaseServer == DatabaseServer.PostgreSql)
         {
-            if (_queries[batchSize] != null)
-            {
-                return _queries[batchSize];
-            }
-
-            var lastIndex = batchSize - 1;
-
-            var sb = StringBuilderCache.Acquire();
-
-            if (DatabaseServer == DatabaseServer.PostgreSql)
-            {
-                sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
-                Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
-                sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
-            }
-            else
-            {
-                Enumerable.Range(0, batchSize).ToList().ForEach(i => sb.Append($"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};"));
-            }
-
-            return _queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb);
+            sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
+            Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
+            sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
         }
+        else
+        {
+            Enumerable.Range(0, batchSize).ToList().ForEach(i => sb.Append($"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};"));
+        }
+
+        return _queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb);
     }
 }

+ 6 - 7
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/CachedWorld.cs

@@ -1,14 +1,13 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public sealed class CachedWorld
 {
-    public sealed class CachedWorld
-    {
-        public int Id { get; set; }
+    public int Id { get; set; }
 
-        public int RandomNumber { get; set; }
+    public int RandomNumber { get; set; }
 
-        public static implicit operator CachedWorld(World world) => new CachedWorld { Id = world.Id, RandomNumber = world.RandomNumber };
-    }
+    public static implicit operator CachedWorld(World world) => new CachedWorld { Id = world.Id, RandomNumber = world.RandomNumber };
 }

+ 11 - 14
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/Fortune.cs

@@ -1,25 +1,22 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
+namespace PlatformBenchmarks;
 
-namespace PlatformBenchmarks
+public readonly struct Fortune : IComparable<Fortune>, IComparable
 {
-    public readonly struct Fortune : IComparable<Fortune>, IComparable
+    public Fortune(int id, string message)
     {
-        public Fortune(int id, string message)
-        {
-            Id = id;
-            Message = message;
-        }
+        Id = id;
+        Message = message;
+    }
 
-        public int Id { get; }
+    public int Id { get; }
 
-        public string Message { get; }
+    public string Message { get; }
 
-        public int CompareTo(object obj) => throw new InvalidOperationException("The non-generic CompareTo should not be used");
+    public int CompareTo(object obj) => throw new InvalidOperationException("The non-generic CompareTo should not be used");
 
-        // Performance critical, using culture insensitive comparison
-        public int CompareTo(Fortune other) => string.CompareOrdinal(Message, other.Message);
-    }
+    // Performance critical, using culture insensitive comparison
+    public int CompareTo(Fortune other) => string.CompareOrdinal(Message, other.Message);
 }

+ 5 - 6
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/JsonMessage.cs

@@ -1,10 +1,9 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public struct JsonMessage
 {
-    public struct JsonMessage
-    {
-        public string message { get; set; }
-    }
-}
+    public string message { get; set; }
+}

+ 17 - 20
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/Random.cs

@@ -1,32 +1,29 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
 using System.Runtime.CompilerServices;
-using System.Threading;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public class ConcurrentRandom
 {
-    public class ConcurrentRandom
-    {
-        private static int nextSeed = 0;
+    private static int nextSeed = 0;
 
-        // Random isn't thread safe
-        [ThreadStatic]
-        private static Random _random;
+    // Random isn't thread safe
+    [ThreadStatic]
+    private static Random _random;
 
-        private static Random Random => _random ?? CreateRandom();
+    private static Random Random => _random ?? CreateRandom();
 
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static Random CreateRandom()
-        {
-            _random = new Random(Interlocked.Increment(ref nextSeed));
-            return _random;
-        }
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    private static Random CreateRandom()
+    {
+        _random = new Random(Interlocked.Increment(ref nextSeed));
+        return _random;
+    }
 
-        public int Next(int minValue, int maxValue)
-        {
-            return Random.Next(minValue, maxValue);
-        }
+    public int Next(int minValue, int maxValue)
+    {
+        return Random.Next(minValue, maxValue);
     }
 }

+ 6 - 7
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Data/World.cs

@@ -3,13 +3,12 @@
 
 using System.Runtime.InteropServices;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+[StructLayout(LayoutKind.Sequential, Size = 8)]
+public struct World
 {
-    [StructLayout(LayoutKind.Sequential, Size = 8)]
-    public struct World
-    {
-        public int Id { get; set; }
+    public int Id { get; set; }
 
-        public int RandomNumber { get; set; }
-    }
+    public int RandomNumber { get; set; }
 }

+ 43 - 45
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/DateHeader.cs

@@ -1,67 +1,65 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Buffers.Text;
 using System.Diagnostics;
 using System.Text;
-using System.Threading;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+/// <summary>
+/// Manages the generation of the date header value.
+/// </summary>
+internal static class DateHeader
 {
-    /// <summary>
-    /// Manages the generation of the date header value.
-    /// </summary>
-    internal static class DateHeader
-    {
-        const int prefixLength = 8; // "\r\nDate: ".Length
-        const int dateTimeRLength = 29; // Wed, 14 Mar 2018 14:20:00 GMT
-        const int suffixLength = 2; // crlf
-        const int suffixIndex = dateTimeRLength + prefixLength;
+    const int prefixLength = 8; // "\r\nDate: ".Length
+    const int dateTimeRLength = 29; // Wed, 14 Mar 2018 14:20:00 GMT
+    const int suffixLength = 2; // crlf
+    const int suffixIndex = dateTimeRLength + prefixLength;
 
-        private static readonly Timer s_timer = new Timer((s) => {
-            SetDateValues(DateTimeOffset.UtcNow);
-        }, null, 1000, 1000);
+    private static readonly Timer s_timer = new((s) =>
+    {
+        SetDateValues(DateTimeOffset.UtcNow);
+    }, null, 1000, 1000);
 
-        private static byte[] s_headerBytesMaster = new byte[prefixLength + dateTimeRLength + 2 * suffixLength];
-        private static byte[] s_headerBytesScratch = new byte[prefixLength + dateTimeRLength + 2 * suffixLength];
+    private static byte[] s_headerBytesMaster = new byte[prefixLength + dateTimeRLength + 2 * suffixLength];
+    private static byte[] s_headerBytesScratch = new byte[prefixLength + dateTimeRLength + 2 * suffixLength];
 
-        static DateHeader()
-        {
-            var utf8 = Encoding.ASCII.GetBytes("\r\nDate: ").AsSpan();
+    static DateHeader()
+    {
+        var utf8 = Encoding.ASCII.GetBytes("\r\nDate: ").AsSpan();
 
-            utf8.CopyTo(s_headerBytesMaster);
-            utf8.CopyTo(s_headerBytesScratch);
-            s_headerBytesMaster[suffixIndex] = (byte)'\r';
-            s_headerBytesMaster[suffixIndex + 1] = (byte)'\n';
-            s_headerBytesMaster[suffixIndex + 2] = (byte)'\r';
-            s_headerBytesMaster[suffixIndex + 3] = (byte)'\n';
-            s_headerBytesScratch[suffixIndex] = (byte)'\r';
-            s_headerBytesScratch[suffixIndex + 1] = (byte)'\n';
-            s_headerBytesScratch[suffixIndex + 2] = (byte)'\r';
-            s_headerBytesScratch[suffixIndex + 3] = (byte)'\n';
+        utf8.CopyTo(s_headerBytesMaster);
+        utf8.CopyTo(s_headerBytesScratch);
+        s_headerBytesMaster[suffixIndex] = (byte)'\r';
+        s_headerBytesMaster[suffixIndex + 1] = (byte)'\n';
+        s_headerBytesMaster[suffixIndex + 2] = (byte)'\r';
+        s_headerBytesMaster[suffixIndex + 3] = (byte)'\n';
+        s_headerBytesScratch[suffixIndex] = (byte)'\r';
+        s_headerBytesScratch[suffixIndex + 1] = (byte)'\n';
+        s_headerBytesScratch[suffixIndex + 2] = (byte)'\r';
+        s_headerBytesScratch[suffixIndex + 3] = (byte)'\n';
 
-            SetDateValues(DateTimeOffset.UtcNow);
-            SyncDateTimer();
-        }
+        SetDateValues(DateTimeOffset.UtcNow);
+        SyncDateTimer();
+    }
 
-        public static void SyncDateTimer() => s_timer.Change(1000, 1000);
+    public static void SyncDateTimer() => s_timer.Change(1000, 1000);
 
-        public static ReadOnlySpan<byte> HeaderBytes => s_headerBytesMaster;
+    public static ReadOnlySpan<byte> HeaderBytes => s_headerBytesMaster;
 
-        private static void SetDateValues(DateTimeOffset value)
+    private static void SetDateValues(DateTimeOffset value)
+    {
+        lock (s_headerBytesScratch)
         {
-            lock (s_headerBytesScratch)
+            if (!Utf8Formatter.TryFormat(value, s_headerBytesScratch.AsSpan(prefixLength), out var written, 'R'))
             {
-                if (!Utf8Formatter.TryFormat(value, s_headerBytesScratch.AsSpan(prefixLength), out var written, 'R'))
-                {
-                    throw new Exception("date time format failed");
-                }
-                Debug.Assert(written == dateTimeRLength);
-                var temp = s_headerBytesMaster;
-                s_headerBytesMaster = s_headerBytesScratch;
-                s_headerBytesScratch = temp;
+                throw new Exception("date time format failed");
             }
+            Debug.Assert(written == dateTimeRLength);
+            var temp = s_headerBytesMaster;
+            s_headerBytesMaster = s_headerBytesScratch;
+            s_headerBytesScratch = temp;
         }
     }
 }

+ 14 - 15
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/HttpApplication.cs

@@ -4,26 +4,25 @@
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Connections;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public static class HttpApplicationConnectionBuilderExtensions
 {
-    public static class HttpApplicationConnectionBuilderExtensions
+    public static IConnectionBuilder UseHttpApplication<TConnection>(this IConnectionBuilder builder) where TConnection : IHttpConnection, new()
     {
-        public static IConnectionBuilder UseHttpApplication<TConnection>(this IConnectionBuilder builder) where TConnection : IHttpConnection, new()
-        {
-            return builder.Use(next => new HttpApplication<TConnection>().ExecuteAsync);
-        }
+        return builder.Use(next => new HttpApplication<TConnection>().ExecuteAsync);
     }
+}
 
-    public class HttpApplication<TConnection> where TConnection : IHttpConnection, new()
+public class HttpApplication<TConnection> where TConnection : IHttpConnection, new()
+{
+    public Task ExecuteAsync(ConnectionContext connection)
     {
-        public Task ExecuteAsync(ConnectionContext connection)
+        var httpConnection = new TConnection
         {
-            var httpConnection = new TConnection
-            {
-                Reader = connection.Transport.Input,
-                Writer = connection.Transport.Output
-            };
-            return httpConnection.ExecuteAsync();
-        }
+            Reader = connection.Transport.Input,
+            Writer = connection.Transport.Output
+        };
+        return httpConnection.ExecuteAsync();
     }
 }

+ 6 - 8
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/IHttpConnection.cs

@@ -2,15 +2,13 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System.IO.Pipelines;
-using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public interface IHttpConnection : IHttpHeadersHandler, IHttpRequestLineHandler
 {
-    public interface IHttpConnection : IHttpHeadersHandler, IHttpRequestLineHandler
-    {
-        PipeReader Reader { get; set; }
-        PipeWriter Writer { get; set; }
-        Task ExecuteAsync();
-    }
+    PipeReader Reader { get; set; }
+    PipeWriter Writer { get; set; }
+    Task ExecuteAsync();
 }

+ 6 - 6
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/PlatformBenchmarks.csproj

@@ -15,6 +15,7 @@
     <EventSourceSupport>false</EventSourceSupport>
     <DebuggerSupport>false</DebuggerSupport>
     <IlcGenerateStackTraceData>false</IlcGenerateStackTraceData>
+    <ImplicitUsings>enable</ImplicitUsings>
   </PropertyGroup>
   
   <PropertyGroup>
@@ -24,17 +25,16 @@
   </PropertyGroup>
   
   <ItemGroup>
-    <PackageReference Condition=" '$(DatabaseProvider)' == 'Npgsql' " Include="Npgsql" Version="6.0.0-rc.2" />
-    <PackageReference Condition=" '$(DatabaseProvider)' == 'MySqlConnector' " Include="MySqlConnector" Version="1.3.13" />
-    <PackageReference Include="Microsoft.DotNet.ILCompiler" Version="7.0.0-*" />
+    <IlcArg Include="--instructionset:sse4.2" />
   </ItemGroup>
 
   <ItemGroup>
-      <None Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
+    <PackageReference Condition=" '$(DatabaseProvider)' == 'Npgsql' " Include="Npgsql" Version="6.0.0" />
+    <PackageReference Condition=" '$(DatabaseProvider)' == 'MySqlConnector' " Include="MySqlConnector" Version="2.0.0" />
+    <PackageReference Include="Microsoft.DotNet.ILCompiler" Version="7.0.0-*" />
   </ItemGroup>
 
   <ItemGroup>
-    <IlcArg Include="--instructionset:sse4.2" />
+      <None Include="appsettings.json" CopyToOutputDirectory="PreserveNewest" />
   </ItemGroup>
-
 </Project>

+ 46 - 52
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Program.cs

@@ -1,54 +1,49 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using System.Net;
 using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public class Program
 {
-    public class Program
-    {
-        public static string[] Args;
+    public static string[] Args;
 
-        public static async Task Main(string[] args)
-        {
-            Args = args;
+    public static async Task Main(string[] args)
+    {
+        Args = args;
 
-            Console.WriteLine(BenchmarkApplication.ApplicationName);
+        Console.WriteLine(BenchmarkApplication.ApplicationName);
 #if !DATABASE
-            Console.WriteLine(BenchmarkApplication.Paths.Plaintext);
-            Console.WriteLine(BenchmarkApplication.Paths.Json);
+        Console.WriteLine(BenchmarkApplication.Paths.Plaintext);
+        Console.WriteLine(BenchmarkApplication.Paths.Json);
 #else
             Console.WriteLine(BenchmarkApplication.Paths.Fortunes);
             Console.WriteLine(BenchmarkApplication.Paths.SingleQuery);
             Console.WriteLine(BenchmarkApplication.Paths.Updates);
             Console.WriteLine(BenchmarkApplication.Paths.MultipleQueries);
 #endif
-            DateHeader.SyncDateTimer();
+        DateHeader.SyncDateTimer();
 
-            var host = BuildWebHost(args);
-            var config = (IConfiguration)host.Services.GetService(typeof(IConfiguration));
-            BatchUpdateString.DatabaseServer = config.Get<AppSettings>().Database;
+        var host = BuildWebHost(args);
+        var config = (IConfiguration)host.Services.GetService(typeof(IConfiguration));
+        BatchUpdateString.DatabaseServer = config.Get<AppSettings>().Database;
 #if DATABASE
             await BenchmarkApplication.Db.PopulateCache();
 #endif
-            await host.RunAsync();
-        }
+        await host.RunAsync();
+    }
 
-        public static IWebHost BuildWebHost(string[] args)
-        {
-            var config = new ConfigurationBuilder()
-                .AddJsonFile("appsettings.json")
-                .AddEnvironmentVariables()
-                .AddEnvironmentVariables(prefix: "ASPNETCORE_")
-                .AddCommandLine(args)
-                .Build();
-
-            var appSettings = config.Get<AppSettings>();
+    public static IWebHost BuildWebHost(string[] args)
+    {
+        var config = new ConfigurationBuilder()
+            .AddJsonFile("appsettings.json")
+            .AddEnvironmentVariables()
+            .AddEnvironmentVariables(prefix: "ASPNETCORE_")
+            .AddCommandLine(args)
+            .Build();
+
+        var appSettings = config.Get<AppSettings>();
 #if DATABASE
             Console.WriteLine($"Database: {appSettings.Database}");
             Console.WriteLine($"ConnectionString: {appSettings.ConnectionString}");
@@ -64,33 +59,32 @@ namespace PlatformBenchmarks
             }
 #endif
 
-            var hostBuilder = new WebHostBuilder()
-                .UseBenchmarksConfiguration(config)
-                .UseKestrel((context, options) =>
+        var hostBuilder = new WebHostBuilder()
+            .UseBenchmarksConfiguration(config)
+            .UseKestrel((context, options) =>
+            {
+                var endPoint = context.Configuration.CreateIPEndPoint();
+
+                options.Listen(endPoint, builder =>
                 {
-                    var endPoint = context.Configuration.CreateIPEndPoint();
+                    builder.UseHttpApplication<BenchmarkApplication>();
+                });
+            })
+            .UseStartup<Startup>();
 
-                    options.Listen(endPoint, builder =>
-                    {
-                        builder.UseHttpApplication<BenchmarkApplication>();
-                    });
-                })
-                .UseStartup<Startup>();
+        hostBuilder.UseSockets(options =>
+        {
+            options.WaitForDataBeforeAllocatingBuffer = false;
 
-            hostBuilder.UseSockets(options =>
+            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
             {
-                options.WaitForDataBeforeAllocatingBuffer = false;
-
-                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
-                {
-                    options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
-                }
-            });
+                options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
+            }
+        });
 
 
-            var host = hostBuilder.Build();
+        var host = hostBuilder.Build();
 
-            return host;
-        }
+        return host;
     }
 }

+ 3 - 7
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/Startup.cs

@@ -1,15 +1,11 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using Microsoft.AspNetCore.Builder;
+namespace PlatformBenchmarks;
 
-namespace PlatformBenchmarks
+public class Startup
 {
-    public class Startup
+    public void Configure(IApplicationBuilder app)
     {
-        public void Configure(IApplicationBuilder app)
-        {
-        }
     }
 }

+ 36 - 38
frameworks/CSharp/aspnetcore-corert/PlatformBenchmarks/StringBuilderCache.cs

@@ -1,59 +1,57 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
 using System.Text;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+internal static class StringBuilderCache
 {
-    internal static class StringBuilderCache
-    {
-        private const int DefaultCapacity = 1386;
-        private const int MaxBuilderSize = DefaultCapacity * 3;
+    private const int DefaultCapacity = 1386;
+    private const int MaxBuilderSize = DefaultCapacity * 3;
 
-        [ThreadStatic]
-        private static StringBuilder t_cachedInstance;
+    [ThreadStatic]
+    private static StringBuilder t_cachedInstance;
 
-        /// <summary>Get a StringBuilder for the specified capacity.</summary>
-        /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks>
-        public static StringBuilder Acquire(int capacity = DefaultCapacity)
+    /// <summary>Get a StringBuilder for the specified capacity.</summary>
+    /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks>
+    public static StringBuilder Acquire(int capacity = DefaultCapacity)
+    {
+        if (capacity <= MaxBuilderSize)
         {
-            if (capacity <= MaxBuilderSize)
+            StringBuilder sb = t_cachedInstance;
+            if (capacity < DefaultCapacity)
             {
-                StringBuilder sb = t_cachedInstance;
-                if (capacity < DefaultCapacity)
-                {
-                    capacity = DefaultCapacity;
-                }
+                capacity = DefaultCapacity;
+            }
 
-                if (sb != null)
+            if (sb != null)
+            {
+                // Avoid stringbuilder block fragmentation by getting a new StringBuilder
+                // when the requested size is larger than the current capacity
+                if (capacity <= sb.Capacity)
                 {
-                    // Avoid stringbuilder block fragmentation by getting a new StringBuilder
-                    // when the requested size is larger than the current capacity
-                    if (capacity <= sb.Capacity)
-                    {
-                        t_cachedInstance = null;
-                        sb.Clear();
-                        return sb;
-                    }
+                    t_cachedInstance = null;
+                    sb.Clear();
+                    return sb;
                 }
             }
-            return new StringBuilder(capacity);
         }
+        return new StringBuilder(capacity);
+    }
 
-        public static void Release(StringBuilder sb)
+    public static void Release(StringBuilder sb)
+    {
+        if (sb.Capacity <= MaxBuilderSize)
         {
-            if (sb.Capacity <= MaxBuilderSize)
-            {
-                t_cachedInstance = sb;
-            }
+            t_cachedInstance = sb;
         }
+    }
 
-        public static string GetStringAndRelease(StringBuilder sb)
-        {
-            string result = sb.ToString();
-            Release(sb);
-            return result;
-        }
+    public static string GetStringAndRelease(StringBuilder sb)
+    {
+        string result = sb.ToString();
+        Release(sb);
+        return result;
     }
 }

+ 2 - 2
frameworks/CSharp/aspnetcore-corert/aspcore-corert-ado-pg-up.dockerfile

@@ -1,11 +1,11 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 RUN apt-get update
 RUN apt-get -yqq install clang zlib1g-dev libkrb5-dev
 WORKDIR /app
 COPY PlatformBenchmarks .
 RUN dotnet publish -c Release -o out /p:DatabaseProvider=Npgsql -r linux-x64
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 WORKDIR /app

+ 2 - 2
frameworks/CSharp/aspnetcore-corert/aspcore-corert-ado-pg.dockerfile

@@ -1,11 +1,11 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 RUN apt-get update
 RUN apt-get -yqq install clang zlib1g-dev libkrb5-dev
 WORKDIR /app
 COPY PlatformBenchmarks .
 RUN dotnet publish -c Release -o out /p:DatabaseProvider=Npgsql -r linux-x64
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 WORKDIR /app

+ 2 - 2
frameworks/CSharp/aspnetcore-corert/aspcore-corert.dockerfile

@@ -1,11 +1,11 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 RUN apt-get update
 RUN apt-get -yqq install clang zlib1g-dev libkrb5-dev
 WORKDIR /app
 COPY PlatformBenchmarks .
 RUN dotnet publish -c Release -o out -r linux-x64
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 ENV DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS 1
 WORKDIR /app

+ 5 - 4
frameworks/CSharp/aspnetcore/Benchmarks/Benchmarks.csproj

@@ -2,6 +2,7 @@
   <PropertyGroup>
     <TargetFramework>net6.0</TargetFramework>
     <OutputType>Exe</OutputType>
+    <ImplicitUsings>enable</ImplicitUsings>
   </PropertyGroup>
 
   <ItemGroup>
@@ -12,10 +13,10 @@
   </ItemGroup>
 
   <ItemGroup>
-    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0-rc.2.21480.5" />
+    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="6.0.0" />
 
-    <PackageReference Include="Dapper" Version="2.0.90" />
-    <PackageReference Include="MySqlConnector" Version="1.3.13" />
-    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.0-rc.2" />
+    <PackageReference Include="Dapper" Version="2.0.123" />
+    <PackageReference Include="MySqlConnector" Version="2.0.0" />
+    <PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.0" />
   </ItemGroup>
 </Project>

+ 5 - 6
frameworks/CSharp/aspnetcore/Benchmarks/Configuration/AppSettings.cs

@@ -1,12 +1,11 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace Benchmarks.Configuration
+namespace Benchmarks.Configuration;
+
+public class AppSettings
 {
-    public class AppSettings
-    {
-        public string ConnectionString { get; set; }
+    public string ConnectionString { get; set; }
 
-        public DatabaseServer Database { get; set; } = DatabaseServer.None;
-    }
+    public DatabaseServer Database { get; set; } = DatabaseServer.None;
 }

+ 7 - 8
frameworks/CSharp/aspnetcore/Benchmarks/Configuration/ConsoleArgs.cs

@@ -1,15 +1,14 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-namespace Benchmarks.Configuration
+namespace Benchmarks.Configuration;
+
+public class ConsoleArgs
 {
-    public class ConsoleArgs
+    public ConsoleArgs(string[] args)
     {
-        public ConsoleArgs(string[] args)
-        {
-            Args = args;
-        }
-
-        public string[] Args { get; }
+        Args = args;
     }
+
+    public string[] Args { get; }
 }

+ 53 - 59
frameworks/CSharp/aspnetcore/Benchmarks/Configuration/ConsoleHostScenariosConfiguration.cs

@@ -1,85 +1,79 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.Extensions.Configuration;
+namespace Benchmarks.Configuration;
 
-namespace Benchmarks.Configuration
+public class ConsoleHostScenariosConfiguration : IScenariosConfiguration
 {
-    public class ConsoleHostScenariosConfiguration : IScenariosConfiguration
+    private readonly string[] _args;
+
+    public ConsoleHostScenariosConfiguration(ConsoleArgs args)
     {
-        private readonly string[] _args;
+        _args = args.Args;
+    }
 
-        public ConsoleHostScenariosConfiguration(ConsoleArgs args)
-        {
-            _args = args.Args;
-        }
+    public void ConfigureScenarios(Scenarios scenarios)
+    {
+        var scenarioConfig = new ConfigurationBuilder()
+            .AddJsonFile("scenarios.json", optional: true)
+            .AddCommandLine(_args)
+            .Build();
 
-        public void ConfigureScenarios(Scenarios scenarios)
+        var enabledCount = 0;
+        var configuredScenarios = scenarioConfig["scenarios"];
+        if (!string.IsNullOrWhiteSpace(configuredScenarios))
         {
-            var scenarioConfig = new ConfigurationBuilder()
-                .AddJsonFile("scenarios.json", optional: true)
-                .AddCommandLine(_args)
-                .Build();
-
-            var enabledCount = 0;
-            var configuredScenarios = scenarioConfig["scenarios"];
-            if (!string.IsNullOrWhiteSpace(configuredScenarios))
+            Console.WriteLine("Scenario configuration found in scenarios.json and/or command line args");
+            var choices = configuredScenarios.Split(',');
+            foreach (var choice in choices)
             {
-                Console.WriteLine("Scenario configuration found in scenarios.json and/or command line args");
-                var choices = configuredScenarios.Split(',');
-                foreach (var choice in choices)
-                {
-                    enabledCount += scenarios.Enable(choice);
-                }
+                enabledCount += scenarios.Enable(choice);
             }
-            else
+        }
+        else
+        {
+            Console.WriteLine("Which scenarios would you like to enable?:");
+            Console.WriteLine();
+            foreach (var scenario in Scenarios.GetNames())
             {
-                Console.WriteLine("Which scenarios would you like to enable?:");
-                Console.WriteLine();
-                foreach (var scenario in Scenarios.GetNames())
-                {
-                    Console.WriteLine("  " + scenario);
-                }
-                Console.WriteLine();
-                Console.WriteLine("Type full or partial scenario names separated by commas and hit [Enter]");
-                Console.Write("> ");
+                Console.WriteLine("  " + scenario);
+            }
+            Console.WriteLine();
+            Console.WriteLine("Type full or partial scenario names separated by commas and hit [Enter]");
+            Console.Write("> ");
 
-                var choices = Console.ReadLine().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
+            var choices = Console.ReadLine().Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
 
-                if (choices.Length > 0)
+            if (choices.Length > 0)
+            {
+                foreach (var choice in choices)
                 {
-                    foreach (var choice in choices)
-                    {
-                        enabledCount += scenarios.Enable(choice);
-                    }
+                    enabledCount += scenarios.Enable(choice);
                 }
             }
-
-            if (enabledCount == 0)
-            {
-                Console.WriteLine();
-                Console.WriteLine("No matching scenarios found, enabling defaults");
-                scenarios.EnableDefault();
-            }
-
-            PrintEnabledScenarios(scenarios.GetEnabled());
         }
 
-        private static void PrintEnabledScenarios(IEnumerable<EnabledScenario> scenarios)
+        if (enabledCount == 0)
         {
             Console.WriteLine();
-            Console.WriteLine("The following scenarios were enabled:");
+            Console.WriteLine("No matching scenarios found, enabling defaults");
+            scenarios.EnableDefault();
+        }
 
-            var maxNameLength = scenarios.Max(s => s.Name.Length);
+        PrintEnabledScenarios(scenarios.GetEnabled());
+    }
 
-            foreach (var scenario in scenarios)
-            {
-                Console.WriteLine($"  {scenario.Name.PadRight(maxNameLength)} -> {string.Join($"{Environment.NewLine}{"".PadLeft(maxNameLength + 6)}", scenario.Paths)}");
-            }
-            Console.WriteLine();
+    private static void PrintEnabledScenarios(IEnumerable<EnabledScenario> scenarios)
+    {
+        Console.WriteLine();
+        Console.WriteLine("The following scenarios were enabled:");
+
+        var maxNameLength = scenarios.Max(s => s.Name.Length);
+
+        foreach (var scenario in scenarios)
+        {
+            Console.WriteLine($"  {scenario.Name.PadRight(maxNameLength)} -> {string.Join($"{Environment.NewLine}{"".PadLeft(maxNameLength + 6)}", scenario.Paths)}");
         }
+        Console.WriteLine();
     }
 }

+ 7 - 8
frameworks/CSharp/aspnetcore/Benchmarks/Configuration/DatabaseServer.cs

@@ -2,13 +2,12 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
 
-namespace Benchmarks.Configuration
+namespace Benchmarks.Configuration;
+
+public enum DatabaseServer
 {
-    public enum DatabaseServer
-    {
-        None,
-        SqlServer,
-        PostgreSql,
-        MySql
-    }
+    None,
+    SqlServer,
+    PostgreSql,
+    MySql
 }

+ 8 - 11
frameworks/CSharp/aspnetcore/Benchmarks/Configuration/EnabledScenario.cs

@@ -1,20 +1,17 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System.Collections.Generic;
+namespace Benchmarks.Configuration;
 
-namespace Benchmarks.Configuration
+public class EnabledScenario
 {
-    public class EnabledScenario
+    public EnabledScenario(string name, IEnumerable<string> paths)
     {
-        public EnabledScenario(string name, IEnumerable<string> paths)
-        {
-            Name = name;
-            Paths = paths;
-        }
+        Name = name;
+        Paths = paths;
+    }
 
-        public string Name { get; }
+    public string Name { get; }
 
-        public IEnumerable<string> Paths { get; }
-    }
+    public IEnumerable<string> Paths { get; }
 }

+ 4 - 5
frameworks/CSharp/aspnetcore/Benchmarks/Configuration/IScenariosConfiguration.cs

@@ -1,10 +1,9 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace Benchmarks.Configuration
+namespace Benchmarks.Configuration;
+
+public interface IScenariosConfiguration
 {
-    public interface IScenariosConfiguration
-    {
-        void ConfigureScenarios(Scenarios scenarios);
-    }
+    void ConfigureScenarios(Scenarios scenarios);
 }

+ 107 - 112
frameworks/CSharp/aspnetcore/Benchmarks/Configuration/Scenarios.cs

@@ -1,168 +1,163 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using System.Collections.Generic;
-using System.Linq;
 using System.Linq.Expressions;
 using System.Reflection;
 using Microsoft.EntityFrameworkCore.Infrastructure;
-using Microsoft.EntityFrameworkCore.Internal;
 
-namespace Benchmarks.Configuration
+namespace Benchmarks.Configuration;
+
+public class Scenarios
 {
-    public class Scenarios
+    public Scenarios(IScenariosConfiguration scenariosConfiguration)
     {
-        public Scenarios(IScenariosConfiguration scenariosConfiguration)
-        {
-            scenariosConfiguration.ConfigureScenarios(this);
-        }
+        scenariosConfiguration.ConfigureScenarios(this);
+    }
 
-        [ScenarioPath("/plaintext")]
-        public bool Plaintext { get; set; }
+    [ScenarioPath("/plaintext")]
+    public bool Plaintext { get; set; }
 
-        [ScenarioPath("/json")]
-        public bool Json { get; set; }
+    [ScenarioPath("/json")]
+    public bool Json { get; set; }
 
-        [ScenarioPath("/128B.txt", "/512B.txt", "/1KB.txt", "/4KB.txt", "/16KB.txt", "/512KB.txt", "/1MB.txt", "/5MB.txt")]
-        public bool StaticFiles { get; set; }
+    [ScenarioPath("/128B.txt", "/512B.txt", "/1KB.txt", "/4KB.txt", "/16KB.txt", "/512KB.txt", "/1MB.txt", "/5MB.txt")]
+    public bool StaticFiles { get; set; }
 
-        [ScenarioPath("/db/raw")]
-        public bool DbSingleQueryRaw { get; set; }
+    [ScenarioPath("/db/raw")]
+    public bool DbSingleQueryRaw { get; set; }
 
-        [ScenarioPath("/db/ef")]
-        public bool DbSingleQueryEf { get; set; }
+    [ScenarioPath("/db/ef")]
+    public bool DbSingleQueryEf { get; set; }
 
-        [ScenarioPath("/db/dapper")]
-        public bool DbSingleQueryDapper { get; set; }
+    [ScenarioPath("/db/dapper")]
+    public bool DbSingleQueryDapper { get; set; }
 
-        [ScenarioPath("/queries/raw")]
-        public bool DbMultiQueryRaw { get; set; }
+    [ScenarioPath("/queries/raw")]
+    public bool DbMultiQueryRaw { get; set; }
 
-        [ScenarioPath("/queries/ef")]
-        public bool DbMultiQueryEf { get; set; }
+    [ScenarioPath("/queries/ef")]
+    public bool DbMultiQueryEf { get; set; }
 
-        [ScenarioPath("/queries/dapper")]
-        public bool DbMultiQueryDapper { get; set; }
+    [ScenarioPath("/queries/dapper")]
+    public bool DbMultiQueryDapper { get; set; }
 
-        [ScenarioPath("/updates/raw")]
-        public bool DbMultiUpdateRaw { get; set; }
+    [ScenarioPath("/updates/raw")]
+    public bool DbMultiUpdateRaw { get; set; }
 
-        [ScenarioPath("/updates/ef")]
-        public bool DbMultiUpdateEf { get; set; }
+    [ScenarioPath("/updates/ef")]
+    public bool DbMultiUpdateEf { get; set; }
 
-        [ScenarioPath("/updates/dapper")]
-        public bool DbMultiUpdateDapper { get; set; }
+    [ScenarioPath("/updates/dapper")]
+    public bool DbMultiUpdateDapper { get; set; }
 
-        [ScenarioPath("/fortunes/raw")]
-        public bool DbFortunesRaw { get; set; }
+    [ScenarioPath("/fortunes/raw")]
+    public bool DbFortunesRaw { get; set; }
 
-        [ScenarioPath("/fortunes/ef")]
-        public bool DbFortunesEf { get; set; }
+    [ScenarioPath("/fortunes/ef")]
+    public bool DbFortunesEf { get; set; }
 
-        [ScenarioPath("/fortunes/dapper")]
-        public bool DbFortunesDapper { get; set; }
+    [ScenarioPath("/fortunes/dapper")]
+    public bool DbFortunesDapper { get; set; }
 
-        [ScenarioPath("/mvc/plaintext")]
-        public bool MvcPlaintext { get; set; }
+    [ScenarioPath("/mvc/plaintext")]
+    public bool MvcPlaintext { get; set; }
 
-        [ScenarioPath("/mvc/json")]
-        public bool MvcJson { get; set; }
+    [ScenarioPath("/mvc/json")]
+    public bool MvcJson { get; set; }
 
-        [ScenarioPath("/mvc/view")]
-        public bool MvcViews { get; set; }
+    [ScenarioPath("/mvc/view")]
+    public bool MvcViews { get; set; }
 
-        [ScenarioPath("/mvc/db/raw")]
-        public bool MvcDbSingleQueryRaw { get; set; }
+    [ScenarioPath("/mvc/db/raw")]
+    public bool MvcDbSingleQueryRaw { get; set; }
 
-        [ScenarioPath("/mvc/db/dapper")]
-        public bool MvcDbSingleQueryDapper { get; set; }
+    [ScenarioPath("/mvc/db/dapper")]
+    public bool MvcDbSingleQueryDapper { get; set; }
 
-        [ScenarioPath("/mvc/db/ef")]
-        public bool MvcDbSingleQueryEf { get; set; }
+    [ScenarioPath("/mvc/db/ef")]
+    public bool MvcDbSingleQueryEf { get; set; }
 
-        [ScenarioPath("/mvc/queries/raw")]
-        public bool MvcDbMultiQueryRaw { get; set; }
+    [ScenarioPath("/mvc/queries/raw")]
+    public bool MvcDbMultiQueryRaw { get; set; }
 
-        [ScenarioPath("/mvc/queries/dapper")]
-        public bool MvcDbMultiQueryDapper { get; set; }
+    [ScenarioPath("/mvc/queries/dapper")]
+    public bool MvcDbMultiQueryDapper { get; set; }
 
-        [ScenarioPath("/mvc/queries/ef")]
-        public bool MvcDbMultiQueryEf { get; set; }
+    [ScenarioPath("/mvc/queries/ef")]
+    public bool MvcDbMultiQueryEf { get; set; }
 
-        [ScenarioPath("/mvc/updates/raw")]
-        public bool MvcDbMultiUpdateRaw { get; set; }
+    [ScenarioPath("/mvc/updates/raw")]
+    public bool MvcDbMultiUpdateRaw { get; set; }
 
-        [ScenarioPath("/mvc/updates/dapper")]
-        public bool MvcDbMultiUpdateDapper { get; set; }
+    [ScenarioPath("/mvc/updates/dapper")]
+    public bool MvcDbMultiUpdateDapper { get; set; }
 
-        [ScenarioPath("/mvc/updates/ef")]
-        public bool MvcDbMultiUpdateEf { get; set; }
+    [ScenarioPath("/mvc/updates/ef")]
+    public bool MvcDbMultiUpdateEf { get; set; }
 
-        [ScenarioPath("/mvc/fortunes/raw")]
-        public bool MvcDbFortunesRaw { get; set; }
+    [ScenarioPath("/mvc/fortunes/raw")]
+    public bool MvcDbFortunesRaw { get; set; }
 
-        [ScenarioPath("/mvc/fortunes/ef")]
-        public bool MvcDbFortunesEf { get; set; }
+    [ScenarioPath("/mvc/fortunes/ef")]
+    public bool MvcDbFortunesEf { get; set; }
 
-        [ScenarioPath("/mvc/fortunes/dapper")]
-        public bool MvcDbFortunesDapper { get; set; }
+    [ScenarioPath("/mvc/fortunes/dapper")]
+    public bool MvcDbFortunesDapper { get; set; }
 
-        public bool Any(string partialName) =>
-            typeof(Scenarios).GetTypeInfo().DeclaredProperties
-                .Where(p => p.Name.IndexOf(partialName, StringComparison.Ordinal) >= 0 && (bool)p.GetValue(this))
-                .Any();
+    public bool Any(string partialName) =>
+        typeof(Scenarios).GetTypeInfo().DeclaredProperties
+            .Where(p => p.Name.IndexOf(partialName, StringComparison.Ordinal) >= 0 && (bool)p.GetValue(this))
+            .Any();
 
-        public IEnumerable<EnabledScenario> GetEnabled() =>
-            typeof(Scenarios).GetTypeInfo().DeclaredProperties
-                .Where(p => p.GetValue(this) is bool && (bool)p.GetValue(this))
-                .Select(p => new EnabledScenario(p.Name, p.GetCustomAttribute<ScenarioPathAttribute>()?.Paths));
+    public IEnumerable<EnabledScenario> GetEnabled() =>
+        typeof(Scenarios).GetTypeInfo().DeclaredProperties
+            .Where(p => p.GetValue(this) is bool && (bool)p.GetValue(this))
+            .Select(p => new EnabledScenario(p.Name, p.GetCustomAttribute<ScenarioPathAttribute>()?.Paths));
 
-        public static IEnumerable<string> GetNames() =>
-            typeof(Scenarios).GetTypeInfo().DeclaredProperties
-                .Select(p => p.Name);
+    public static IEnumerable<string> GetNames() =>
+        typeof(Scenarios).GetTypeInfo().DeclaredProperties
+            .Select(p => p.Name);
 
-        public static string[] GetPaths(Expression<Func<Scenarios, bool>> scenarioExpression) =>
-            scenarioExpression.GetPropertyAccess().GetCustomAttribute<ScenarioPathAttribute>().Paths;
+    public static string[] GetPaths(Expression<Func<Scenarios, bool>> scenarioExpression) =>
+        scenarioExpression.GetPropertyAccess().GetCustomAttribute<ScenarioPathAttribute>().Paths;
 
-        public static string GetPath(Expression<Func<Scenarios, bool>> scenarioExpression) =>
-            GetPaths(scenarioExpression)[0];
+    public static string GetPath(Expression<Func<Scenarios, bool>> scenarioExpression) =>
+        GetPaths(scenarioExpression)[0];
 
-        public int Enable(string partialName)
+    public int Enable(string partialName)
+    {
+        if (string.Equals(partialName, "[default]", StringComparison.OrdinalIgnoreCase))
         {
-            if (string.Equals(partialName, "[default]", StringComparison.OrdinalIgnoreCase))
-            {
-                EnableDefault();
-                return 2;
-            }
-
-            var props = typeof(Scenarios).GetTypeInfo().DeclaredProperties
-                .Where(p => string.Equals(partialName, "[all]", StringComparison.OrdinalIgnoreCase) || p.Name.StartsWith(partialName, StringComparison.OrdinalIgnoreCase))
-                .ToList();
-
-            foreach (var p in props)
-            {
-                p.SetValue(this, true);
-            }
-
-            return props.Count;
+            EnableDefault();
+            return 2;
         }
 
-        public void EnableDefault()
+        var props = typeof(Scenarios).GetTypeInfo().DeclaredProperties
+            .Where(p => string.Equals(partialName, "[all]", StringComparison.OrdinalIgnoreCase) || p.Name.StartsWith(partialName, StringComparison.OrdinalIgnoreCase))
+            .ToList();
+
+        foreach (var p in props)
         {
-            Plaintext = true;
-            Json = true;
+            p.SetValue(this, true);
         }
+
+        return props.Count;
     }
 
-    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
-    public sealed class ScenarioPathAttribute : Attribute
+    public void EnableDefault()
     {
-        public ScenarioPathAttribute(params string[] paths)
-        {
-            Paths = paths;
-        }
+        Plaintext = true;
+        Json = true;
+    }
+}
 
-        public string[] Paths { get; }
+[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
+public sealed class ScenarioPathAttribute : Attribute
+{
+    public ScenarioPathAttribute(params string[] paths)
+    {
+        Paths = paths;
     }
+
+    public string[] Paths { get; }
 }

+ 20 - 23
frameworks/CSharp/aspnetcore/Benchmarks/Controllers/FortunesController.cs

@@ -1,35 +1,32 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System.Threading.Tasks;
 using Benchmarks.Data;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Controllers
+namespace Benchmarks.Controllers;
+
+[Route("mvc/fortunes")]
+public class FortunesController : Controller
 {
-    [Route("mvc/fortunes")]
-    public class FortunesController : Controller
+    [HttpGet("raw")]
+    public async Task<IActionResult> Raw()
     {
-        [HttpGet("raw")]
-        public async Task<IActionResult> Raw()
-        {
-            var db = HttpContext.RequestServices.GetRequiredService<RawDb>();
-            return View("Fortunes", await db.LoadFortunesRows());
-        }
+        var db = HttpContext.RequestServices.GetRequiredService<RawDb>();
+        return View("Fortunes", await db.LoadFortunesRows());
+    }
 
-        [HttpGet("dapper")]
-        public async Task<IActionResult> Dapper()
-        {
-            var db = HttpContext.RequestServices.GetRequiredService<DapperDb>();
-            return View("Fortunes", await db.LoadFortunesRows());
-        }
+    [HttpGet("dapper")]
+    public async Task<IActionResult> Dapper()
+    {
+        var db = HttpContext.RequestServices.GetRequiredService<DapperDb>();
+        return View("Fortunes", await db.LoadFortunesRows());
+    }
 
-        [HttpGet("ef")]
-        public async Task<IActionResult> Ef()
-        {
-            var db = HttpContext.RequestServices.GetRequiredService<EfDb>();
-            return View("Fortunes", await db.LoadFortunesRows());
-        }
+    [HttpGet("ef")]
+    public async Task<IActionResult> Ef()
+    {
+        var db = HttpContext.RequestServices.GetRequiredService<EfDb>();
+        return View("Fortunes", await db.LoadFortunesRows());
     }
 }

+ 31 - 34
frameworks/CSharp/aspnetcore/Benchmarks/Controllers/HomeController.cs

@@ -2,47 +2,44 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
 using System.Text;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 
-namespace Benchmarks.Controllers
+namespace Benchmarks.Controllers;
+
+[Route("mvc")]
+public class HomeController : Controller
 {
-    [Route("mvc")]
-    public class HomeController : Controller
+    [HttpGet("plaintext")]
+    public IActionResult Plaintext()
     {
-        [HttpGet("plaintext")]
-        public IActionResult Plaintext()
-        {
-            return new PlainTextActionResult();
-        }
+        return new PlainTextActionResult();
+    }
 
-        [HttpGet("json")]
-        [Produces("application/json")]
-        public object Json()
-        {
-            return new { message = "Hello, World!" };
-        }
-        
-        [HttpGet("view")]
-        public ViewResult Index()
-        {
-            return View();
-        }
+    [HttpGet("json")]
+    [Produces("application/json")]
+    public object Json()
+    {
+        return new { message = "Hello, World!" };
+    }
 
-        private class PlainTextActionResult : IActionResult
-        {
-            private static readonly byte[] _helloWorldPayload = Encoding.UTF8.GetBytes("Hello, World!");
+    [HttpGet("view")]
+    public ViewResult Index()
+    {
+        return View();
+    }
+
+    private class PlainTextActionResult : IActionResult
+    {
+        private static readonly byte[] _helloWorldPayload = Encoding.UTF8.GetBytes("Hello, World!");
 
-            public Task ExecuteResultAsync(ActionContext context)
-            {
-                var response = context.HttpContext.Response;
-                response.StatusCode = StatusCodes.Status200OK;
-                response.ContentType = "text/plain";
-                var payloadLength = _helloWorldPayload.Length;
-                response.ContentLength = payloadLength;
-                return response.Body.WriteAsync(_helloWorldPayload, 0, payloadLength);
-            }
+        public Task ExecuteResultAsync(ActionContext context)
+        {
+            var response = context.HttpContext.Response;
+            response.StatusCode = StatusCodes.Status200OK;
+            response.ContentType = "text/plain";
+            var payloadLength = _helloWorldPayload.Length;
+            response.ContentLength = payloadLength;
+            return response.Body.WriteAsync(_helloWorldPayload, 0, payloadLength);
         }
     }
 }

+ 26 - 29
frameworks/CSharp/aspnetcore/Benchmarks/Controllers/MultipleQueriesController.cs

@@ -1,42 +1,39 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System.Threading.Tasks;
 using Benchmarks.Data;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Controllers
+namespace Benchmarks.Controllers;
+
+[Route("mvc/queries")]
+public class MultipleQueriesController : Controller
 {
-    [Route("mvc/queries")]
-    public class MultipleQueriesController : Controller
+    [HttpGet("raw")]
+    [Produces("application/json")]
+    public Task<World[]> Raw(int queries = 1)
     {
-        [HttpGet("raw")]
-        [Produces("application/json")]
-        public Task<World[]> Raw(int queries = 1)
-        {
-            return ExecuteQuery<RawDb>(queries);
-        }
+        return ExecuteQuery<RawDb>(queries);
+    }
 
-        [HttpGet("dapper")]
-        [Produces("application/json")]
-        public Task<World[]> Dapper(int queries = 1)
-        {
-            return ExecuteQuery<DapperDb>(queries);
-        }
+    [HttpGet("dapper")]
+    [Produces("application/json")]
+    public Task<World[]> Dapper(int queries = 1)
+    {
+        return ExecuteQuery<DapperDb>(queries);
+    }
 
-        [HttpGet("ef")]
-        [Produces("application/json")]
-        public Task<World[]> Ef(int queries = 1)
-        {
-            return ExecuteQuery<EfDb>(queries);
-        }
+    [HttpGet("ef")]
+    [Produces("application/json")]
+    public Task<World[]> Ef(int queries = 1)
+    {
+        return ExecuteQuery<EfDb>(queries);
+    }
 
-        private Task<World[]> ExecuteQuery<T>(int queries) where T : IDb
-        {
-            queries = queries < 1 ? 1 : queries > 500 ? 500 : queries;
-            var db = HttpContext.RequestServices.GetRequiredService<T>();
-            return db.LoadMultipleQueriesRows(queries);
-        }
+    private Task<World[]> ExecuteQuery<T>(int queries) where T : IDb
+    {
+        queries = queries < 1 ? 1 : queries > 500 ? 500 : queries;
+        var db = HttpContext.RequestServices.GetRequiredService<T>();
+        return db.LoadMultipleQueriesRows(queries);
     }
 }

+ 26 - 29
frameworks/CSharp/aspnetcore/Benchmarks/Controllers/MultipleUpdatesController.cs

@@ -1,42 +1,39 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System.Threading.Tasks;
 using Benchmarks.Data;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Controllers
+namespace Benchmarks.Controllers;
+
+[Route("mvc/updates")]
+public class MultipleUpdatesController : Controller
 {
-    [Route("mvc/updates")]
-    public class MultipleUpdatesController : Controller
+    [HttpGet("raw")]
+    [Produces("application/json")]
+    public Task<World[]> Raw(int queries = 1)
     {
-        [HttpGet("raw")]
-        [Produces("application/json")]
-        public Task<World[]> Raw(int queries = 1)
-        {
-            return ExecuteQuery<RawDb>(queries);
-        }
+        return ExecuteQuery<RawDb>(queries);
+    }
 
-        [HttpGet("dapper")]
-        [Produces("application/json")]
-        public Task<World[]> Dapper(int queries = 1)
-        {
-            return ExecuteQuery<DapperDb>(queries);
-        }
+    [HttpGet("dapper")]
+    [Produces("application/json")]
+    public Task<World[]> Dapper(int queries = 1)
+    {
+        return ExecuteQuery<DapperDb>(queries);
+    }
 
-        [HttpGet("ef")]
-        [Produces("application/json")]
-        public Task<World[]> Ef(int queries = 1)
-        {
-            return ExecuteQuery<EfDb>(queries);
-        }
+    [HttpGet("ef")]
+    [Produces("application/json")]
+    public Task<World[]> Ef(int queries = 1)
+    {
+        return ExecuteQuery<EfDb>(queries);
+    }
 
-        private Task<World[]> ExecuteQuery<T>(int queries) where T : IDb
-        {
-            queries = queries < 1 ? 1 : queries > 500 ? 500 : queries;
-            var db = HttpContext.RequestServices.GetRequiredService<T>();
-            return db.LoadMultipleUpdatesRows(queries);
-        }
+    private Task<World[]> ExecuteQuery<T>(int queries) where T : IDb
+    {
+        queries = queries < 1 ? 1 : queries > 500 ? 500 : queries;
+        var db = HttpContext.RequestServices.GetRequiredService<T>();
+        return db.LoadMultipleUpdatesRows(queries);
     }
 }

+ 25 - 28
frameworks/CSharp/aspnetcore/Benchmarks/Controllers/SingleQueryController.cs

@@ -1,41 +1,38 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System.Threading.Tasks;
 using Benchmarks.Data;
 using Microsoft.AspNetCore.Mvc;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Controllers
+namespace Benchmarks.Controllers;
+
+[Route("mvc/db")]
+public class SingleQueryController : Controller
 {
-    [Route("mvc/db")]
-    public class SingleQueryController : Controller
+    [HttpGet("raw")]
+    [Produces("application/json")]
+    public Task<World> Raw()
     {
-        [HttpGet("raw")]
-        [Produces("application/json")]
-        public Task<World> Raw()
-        {
-            return ExecuteQuery<RawDb>();
-        }
+        return ExecuteQuery<RawDb>();
+    }
 
-        [HttpGet("dapper")]
-        [Produces("application/json")]
-        public Task<World> Dapper()
-        {
-            return ExecuteQuery<DapperDb>();
-        }
+    [HttpGet("dapper")]
+    [Produces("application/json")]
+    public Task<World> Dapper()
+    {
+        return ExecuteQuery<DapperDb>();
+    }
 
-        [HttpGet("ef")]
-        [Produces("application/json")]
-        public Task<World> Ef()
-        {
-            return ExecuteQuery<EfDb>();
-        }
+    [HttpGet("ef")]
+    [Produces("application/json")]
+    public Task<World> Ef()
+    {
+        return ExecuteQuery<EfDb>();
+    }
 
-        private Task<World> ExecuteQuery<T>() where T : IDb
-        {
-            var db = HttpContext.RequestServices.GetRequiredService<T>();
-            return db.LoadSingleQueryRow();
-        }
+    private Task<World> ExecuteQuery<T>() where T : IDb
+    {
+        var db = HttpContext.RequestServices.GetRequiredService<T>();
+        return db.LoadSingleQueryRow();
     }
 }

+ 10 - 11
frameworks/CSharp/aspnetcore/Benchmarks/Data/ApplicationDbContext.cs

@@ -3,19 +3,18 @@
 
 using Microsoft.EntityFrameworkCore;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+public sealed class ApplicationDbContext : DbContext
 {
-    public sealed class ApplicationDbContext : DbContext
+    public ApplicationDbContext(DbContextOptions options)
+        : base(options)
     {
-        public ApplicationDbContext(DbContextOptions options)
-            : base(options)
-        {
-            ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
-            ChangeTracker.AutoDetectChangesEnabled = false;
-        }
+        ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
+        ChangeTracker.AutoDetectChangesEnabled = false;
+    }
 
-        public DbSet<World> World { get; set; }
+    public DbSet<World> World { get; set; }
 
-        public DbSet<Fortune> Fortune { get; set; }
-    }
+    public DbSet<Fortune> Fortune { get; set; }
 }

+ 26 - 30
frameworks/CSharp/aspnetcore/Benchmarks/Data/BatchUpdateString.cs

@@ -2,43 +2,39 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
 using Benchmarks.Configuration;
-using System.Collections.Generic;
-using System.Linq;
-using System.Runtime.CompilerServices;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+internal class BatchUpdateString
 {
-    internal class BatchUpdateString
+    private const int MaxBatch = 500;
+
+    private static readonly string[] _queries = new string[MaxBatch + 1];
+
+    public static DatabaseServer DatabaseServer;
+
+    public static string Query(int batchSize)
     {
-        private const int MaxBatch = 500;
+        if (_queries[batchSize] != null)
+        {
+            return _queries[batchSize];
+        }
 
-        private static string[] _queries = new string[MaxBatch+1];
+        var lastIndex = batchSize - 1;
 
-        public static DatabaseServer DatabaseServer;
+        var sb = StringBuilderCache.Acquire();
 
-        public static string Query(int batchSize)
+        if (DatabaseServer == DatabaseServer.PostgreSql)
+        {
+            sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
+            Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
+            sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
+        }
+        else
         {
-            if (_queries[batchSize] != null)
-            {
-                return _queries[batchSize];
-            }
-
-            var lastIndex = batchSize - 1;
-
-            var sb = StringBuilderCache.Acquire();
-
-            if (DatabaseServer == DatabaseServer.PostgreSql)
-            {
-                sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
-                Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
-                sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
-            }
-            else
-            {
-                Enumerable.Range(0, batchSize).ToList().ForEach(i => sb.Append($"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};"));
-            }
-
-            return _queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb);
+            Enumerable.Range(0, batchSize).ToList().ForEach(i => sb.Append($"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};"));
         }
+
+        return _queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb);
     }
 }

+ 70 - 76
frameworks/CSharp/aspnetcore/Benchmarks/Data/DapperDb.cs

@@ -1,113 +1,107 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using System.Collections.Generic;
 using System.Data.Common;
 using System.Dynamic;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Dapper;
 using Microsoft.Extensions.Options;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+public class DapperDb : IDb
 {
-    public class DapperDb : IDb
+    private static readonly Comparison<World> WorldSortComparison = (a, b) => a.Id.CompareTo(b.Id);
+
+    private readonly IRandom _random;
+    private readonly DbProviderFactory _dbProviderFactory;
+    private readonly string _connectionString;
+
+    public DapperDb(IRandom random, DbProviderFactory dbProviderFactory, IOptions<AppSettings> appSettings)
     {
-        private static readonly Comparison<World> WorldSortComparison = (a, b) => a.Id.CompareTo(b.Id);
+        _random = random;
+        _dbProviderFactory = dbProviderFactory;
+        _connectionString = appSettings.Value.ConnectionString;
+    }
 
-        private readonly IRandom _random;
-        private readonly DbProviderFactory _dbProviderFactory;
-        private readonly string _connectionString;
+    public async Task<World> LoadSingleQueryRow()
+    {
+        using var db = _dbProviderFactory.CreateConnection();
+        db.ConnectionString = _connectionString;
 
-        public DapperDb(IRandom random, DbProviderFactory dbProviderFactory, IOptions<AppSettings> appSettings)
-        {
-            _random = random;
-            _dbProviderFactory = dbProviderFactory;
-            _connectionString = appSettings.Value.ConnectionString;
-        }
+        // Note: Don't need to open connection if only doing one thing; let dapper do it
+        return await ReadSingleRow(db);
+    }
+
+    Task<World> ReadSingleRow(DbConnection db)
+    {
+        return db.QueryFirstOrDefaultAsync<World>(
+                "SELECT id, randomnumber FROM world WHERE id = @Id",
+                new { Id = _random.Next(1, 10001) });
+    }
 
-        public async Task<World> LoadSingleQueryRow()
+    public async Task<World[]> LoadMultipleQueriesRows(int count)
+    {
+        var results = new World[count];
+        using (var db = _dbProviderFactory.CreateConnection())
         {
-            using (var db = _dbProviderFactory.CreateConnection())
-            {
-                db.ConnectionString = _connectionString;
+            db.ConnectionString = _connectionString;
+            await db.OpenAsync();
 
-                // Note: Don't need to open connection if only doing one thing; let dapper do it
-                return await ReadSingleRow(db);
+            for (int i = 0; i < count; i++)
+            {
+                results[i] = await ReadSingleRow(db);
             }
         }
 
-        Task<World> ReadSingleRow(DbConnection db)
-        {
-            return db.QueryFirstOrDefaultAsync<World>(
-                    "SELECT id, randomnumber FROM world WHERE id = @Id",
-                    new { Id = _random.Next(1, 10001) });
-        }
+        return results;
+    }
 
-        public async Task<World[]> LoadMultipleQueriesRows(int count)
+    public async Task<World[]> LoadMultipleUpdatesRows(int count)
+    {
+        IDictionary<string, object> parameters = new ExpandoObject();
+
+        using (var db = _dbProviderFactory.CreateConnection())
         {
+            db.ConnectionString = _connectionString;
+            await db.OpenAsync();
+
             var results = new World[count];
-            using (var db = _dbProviderFactory.CreateConnection())
+            for (int i = 0; i < count; i++)
+            {
+                results[i] = await ReadSingleRow(db);
+            }
+
+            for (int i = 0; i < count; i++)
             {
-                db.ConnectionString = _connectionString;
-                await db.OpenAsync();
+                var randomNumber = _random.Next(1, 10001);
+                parameters[$"@Random_{i}"] = randomNumber;
+                parameters[$"@Id_{i}"] = results[i].Id;
 
-                for (int i = 0; i < count; i++)
-                {
-                    results[i] = await ReadSingleRow(db);
-                }
+                results[i].RandomNumber = randomNumber;
             }
 
+            await db.ExecuteAsync(BatchUpdateString.Query(count), parameters);
             return results;
         }
 
-        public async Task<World[]> LoadMultipleUpdatesRows(int count)
-        {
-            IDictionary<string, object> parameters = new ExpandoObject();
-
-            using (var db = _dbProviderFactory.CreateConnection())
-            {
-                db.ConnectionString = _connectionString;
-                await db.OpenAsync();
-
-                var results = new World[count];
-                for (int i = 0; i < count; i++)
-                {
-                    results[i] = await ReadSingleRow(db);
-                }
-
-                for (int i = 0; i < count; i++)
-                {
-                    var randomNumber = _random.Next(1, 10001);
-                    parameters[$"@Random_{i}"] = randomNumber;
-                    parameters[$"@Id_{i}"] = results[i].Id;
-
-                    results[i].RandomNumber = randomNumber;
-                }
-
-                await db.ExecuteAsync(BatchUpdateString.Query(count), parameters);
-                return results;
-            }
+    }
 
-        }
+    public async Task<List<Fortune>> LoadFortunesRows()
+    {
+        List<Fortune> result;
 
-        public async Task<List<Fortune>> LoadFortunesRows()
+        using (var db = _dbProviderFactory.CreateConnection())
         {
-            List<Fortune> result;
-
-            using (var db = _dbProviderFactory.CreateConnection())
-            {
-                db.ConnectionString = _connectionString;
+            db.ConnectionString = _connectionString;
 
-                // Note: don't need to open connection if only doing one thing; let dapper do it
-                result = (await db.QueryAsync<Fortune>("SELECT id, message FROM fortune")).AsList();
-            }
+            // Note: don't need to open connection if only doing one thing; let dapper do it
+            result = (await db.QueryAsync<Fortune>("SELECT id, message FROM fortune")).AsList();
+        }
 
-            result.Add(new Fortune { Message = "Additional fortune added at request time." });
-            result.Sort();
+        result.Add(new Fortune { Message = "Additional fortune added at request time." });
+        result.Sort();
 
-            return result;
-        }
+        return result;
     }
 }

+ 58 - 63
frameworks/CSharp/aspnetcore/Benchmarks/Data/EfDb.cs

@@ -4,94 +4,89 @@
 using Benchmarks.Configuration;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.Options;
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Threading.Tasks;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+public class EfDb : IDb
 {
-    public class EfDb : IDb
+    private readonly IRandom _random;
+    private readonly ApplicationDbContext _dbContext;
+
+    public EfDb(IRandom random, ApplicationDbContext dbContext, IOptions<AppSettings> appSettings)
     {
-        private readonly IRandom _random;
-        private readonly ApplicationDbContext _dbContext;
+        _random = random;
+        _dbContext = dbContext;
+    }
 
-        public EfDb(IRandom random, ApplicationDbContext dbContext, IOptions<AppSettings> appSettings)
-        {
-            _random = random;
-            _dbContext = dbContext;
-        }
+    private static readonly Func<ApplicationDbContext, int, Task<World>> _firstWorldQuery
+        = EF.CompileAsyncQuery((ApplicationDbContext context, int id)
+            => context.World.First(w => w.Id == id));
 
-        private static readonly Func<ApplicationDbContext, int, Task<World>> _firstWorldQuery
-            = EF.CompileAsyncQuery((ApplicationDbContext context, int id)
-                => context.World.First(w => w.Id == id));
+    public Task<World> LoadSingleQueryRow()
+    {
+        var id = _random.Next(1, 10001);
 
-        public Task<World> LoadSingleQueryRow()
-        {
-            var id = _random.Next(1, 10001);
+        return _firstWorldQuery(_dbContext, id);
+    }
 
-            return _firstWorldQuery(_dbContext, id);
-        }
+    public async Task<World[]> LoadMultipleQueriesRows(int count)
+    {
+        var result = new World[count];
 
-        public async Task<World[]> LoadMultipleQueriesRows(int count)
+        for (var i = 0; i < count; i++)
         {
-            var result = new World[count];
+            var id = _random.Next(1, 10001);
 
-            for (var i = 0; i < count; i++)
-            {
-                var id = _random.Next(1, 10001);
+            result[i] = await _firstWorldQuery(_dbContext, id);
+        }
 
-                result[i] = await _firstWorldQuery(_dbContext, id);
-            }
+        return result;
+    }
 
-            return result;
-        }
+    private static readonly Func<ApplicationDbContext, int, Task<World>> _firstWorldTrackedQuery
+        = EF.CompileAsyncQuery((ApplicationDbContext context, int id)
+            => context.World.AsTracking().First(w => w.Id == id));
 
-        private static readonly Func<ApplicationDbContext, int, Task<World>> _firstWorldTrackedQuery
-            = EF.CompileAsyncQuery((ApplicationDbContext context, int id)
-                => context.World.AsTracking().First(w => w.Id == id));
+    public async Task<World[]> LoadMultipleUpdatesRows(int count)
+    {
+        var results = new World[count];
+        var usedIds = new HashSet<int>(count);
 
-        public async Task<World[]> LoadMultipleUpdatesRows(int count)
+        for (var i = 0; i < count; i++)
         {
-            var results = new World[count];
-            var usedIds = new HashSet<int>(count);
-            
-            for (var i = 0; i < count; i++)
+            int id;
+            do
             {
-                int id;
-                do
-                {
-                    id = _random.Next(1, 10001);
-                } while (!usedIds.Add(id));
-                
-                results[i] = await _firstWorldTrackedQuery(_dbContext, id);
-
-                results[i].RandomNumber = _random.Next(1, 10001);
+                id = _random.Next(1, 10001);
+            } while (!usedIds.Add(id));
 
-                _dbContext.Entry(results[i]).State = EntityState.Modified;
-            }
+            results[i] = await _firstWorldTrackedQuery(_dbContext, id);
 
-            await _dbContext.SaveChangesAsync();
+            results[i].RandomNumber = _random.Next(1, 10001);
 
-            return results;
+            _dbContext.Entry(results[i]).State = EntityState.Modified;
         }
 
-        private static readonly Func<ApplicationDbContext, IAsyncEnumerable<Fortune>> _fortunesQuery
-            = EF.CompileAsyncQuery((ApplicationDbContext context) => context.Fortune);
+        await _dbContext.SaveChangesAsync();
 
-        public async Task<List<Fortune>> LoadFortunesRows()
-        {
-            var result = new List<Fortune>();
+        return results;
+    }
 
-            await foreach (var element in _fortunesQuery(_dbContext))
-            {
-                result.Add(element);
-            }
+    private static readonly Func<ApplicationDbContext, IAsyncEnumerable<Fortune>> _fortunesQuery
+        = EF.CompileAsyncQuery((ApplicationDbContext context) => context.Fortune);
 
-            result.Add(new Fortune { Message = "Additional fortune added at request time." });
-            result.Sort();
+    public async Task<List<Fortune>> LoadFortunesRows()
+    {
+        var result = new List<Fortune>();
 
-            return result;
+        await foreach (var element in _fortunesQuery(_dbContext))
+        {
+            result.Add(element);
         }
+
+        result.Add(new Fortune { Message = "Additional fortune added at request time." });
+        result.Sort();
+
+        return result;
     }
 }

+ 18 - 20
frameworks/CSharp/aspnetcore/Benchmarks/Data/Fortune.cs

@@ -1,32 +1,30 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
 using System.ComponentModel.DataAnnotations;
 using System.ComponentModel.DataAnnotations.Schema;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+[Table("fortune")]
+public class Fortune : IComparable<Fortune>, IComparable
 {
-    [Table("fortune")]
-    public class Fortune : IComparable<Fortune>, IComparable
-    {
-        [Column("id")]
-        public int Id { get; set; }
+    [Column("id")]
+    public int Id { get; set; }
 
-        [Column("message")]
-        [StringLength(2048)]
-        [Required]
-        public string Message { get; set; }
+    [Column("message")]
+    [StringLength(2048)]
+    [Required]
+    public string Message { get; set; }
 
-        public int CompareTo(object obj)
-        {
-            return CompareTo((Fortune)obj);
-        }
+    public int CompareTo(object obj)
+    {
+        return CompareTo((Fortune)obj);
+    }
 
-        public int CompareTo(Fortune other)
-        {
-            // Performance critical, using culture insensitive comparison
-            return String.CompareOrdinal(Message, other.Message);
-        }
+    public int CompareTo(Fortune other)
+    {
+        // Performance critical, using culture insensitive comparison
+        return String.CompareOrdinal(Message, other.Message);
     }
 }

+ 6 - 10
frameworks/CSharp/aspnetcore/Benchmarks/Data/IDb.cs

@@ -1,19 +1,15 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System.Collections.Generic;
-using System.Threading.Tasks;
+namespace Benchmarks.Data;
 
-namespace Benchmarks.Data
+public interface IDb
 {
-    public interface IDb
-    {
-        Task<World> LoadSingleQueryRow();
+    Task<World> LoadSingleQueryRow();
 
-        Task<World[]> LoadMultipleQueriesRows(int count);
+    Task<World[]> LoadMultipleQueriesRows(int count);
 
-        Task<World[]> LoadMultipleUpdatesRows(int count);
+    Task<World[]> LoadMultipleUpdatesRows(int count);
 
-        Task<List<Fortune>> LoadFortunesRows();
-    }
+    Task<List<Fortune>> LoadFortunesRows();
 }

+ 4 - 5
frameworks/CSharp/aspnetcore/Benchmarks/Data/IRandom.cs

@@ -1,10 +1,9 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+public interface IRandom
 {
-    public interface IRandom
-    {
-        int Next(int minValue, int maxValue);
-    }
+    int Next(int minValue, int maxValue);
 }

+ 17 - 20
frameworks/CSharp/aspnetcore/Benchmarks/Data/Random.cs

@@ -1,32 +1,29 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
 using System.Runtime.CompilerServices;
-using System.Threading;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+public class DefaultRandom : IRandom
 {
-    public class DefaultRandom : IRandom
-    {
-        private static int nextSeed = 0;
+    private static int nextSeed = 0;
 
-        // Random isn't thread safe
-        [ThreadStatic]
-        private static Random _random;
+    // Random isn't thread safe
+    [ThreadStatic]
+    private static Random _random;
 
-        private static Random Random => _random ?? CreateRandom();
+    private static Random Random => _random ?? CreateRandom();
 
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static Random CreateRandom()
-        {
-            _random = new Random(Interlocked.Increment(ref nextSeed));
-            return _random;
-        }
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    private static Random CreateRandom()
+    {
+        _random = new Random(Interlocked.Increment(ref nextSeed));
+        return _random;
+    }
 
-        public int Next(int minValue, int maxValue)
-        {
-            return Random.Next(minValue, maxValue);
-        }
+    public int Next(int minValue, int maxValue)
+    {
+        return Random.Next(minValue, maxValue);
     }
 }

+ 111 - 127
frameworks/CSharp/aspnetcore/Benchmarks/Data/RawDb.cs

@@ -1,169 +1,153 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using System.Collections.Generic;
 using System.Data;
 using System.Data.Common;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Microsoft.Extensions.Options;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+public class RawDb : IDb
 {
-    public class RawDb : IDb
+    private static readonly Comparison<World> WorldSortComparison = (a, b) => a.Id.CompareTo(b.Id);
+
+    private readonly IRandom _random;
+    private readonly DbProviderFactory _dbProviderFactory;
+    private readonly string _connectionString;
+
+    public RawDb(IRandom random, DbProviderFactory dbProviderFactory, IOptions<AppSettings> appSettings)
     {
-        private static readonly Comparison<World> WorldSortComparison = (a, b) => a.Id.CompareTo(b.Id);
+        _random = random;
+        _dbProviderFactory = dbProviderFactory;
+        _connectionString = appSettings.Value.ConnectionString;
+    }
 
-        private readonly IRandom _random;
-        private readonly DbProviderFactory _dbProviderFactory;
-        private readonly string _connectionString;
+    public async Task<World> LoadSingleQueryRow()
+    {
+        using var db = _dbProviderFactory.CreateConnection();
+        db.ConnectionString = _connectionString;
+        await db.OpenAsync();
 
-        public RawDb(IRandom random, DbProviderFactory dbProviderFactory, IOptions<AppSettings> appSettings)
-        {
-            _random = random;
-            _dbProviderFactory = dbProviderFactory;
-            _connectionString = appSettings.Value.ConnectionString;
-        }
+        using var cmd = CreateReadCommand(db);
+        return await ReadSingleRow(db, cmd);
+    }
 
-        public async Task<World> LoadSingleQueryRow()
+    async Task<World> ReadSingleRow(DbConnection connection, DbCommand cmd)
+    {
+        using (var rdr = await cmd.ExecuteReaderAsync(CommandBehavior.SingleRow))
         {
-            using (var db = _dbProviderFactory.CreateConnection())
-            {
-                db.ConnectionString = _connectionString;
-                await db.OpenAsync();
+            await rdr.ReadAsync();
 
-                using (var cmd = CreateReadCommand(db))
-                {
-                    return await ReadSingleRow(db, cmd);
-                }
-            }
+            return new World
+            {
+                Id = rdr.GetInt32(0),
+                RandomNumber = rdr.GetInt32(1)
+            };
         }
+    }
+
+    DbCommand CreateReadCommand(DbConnection connection)
+    {
+        var cmd = connection.CreateCommand();
+        cmd.CommandText = "SELECT id, randomnumber FROM world WHERE id = @Id";
+        var id = cmd.CreateParameter();
+        id.ParameterName = "@Id";
+        id.DbType = DbType.Int32;
+        id.Value = _random.Next(1, 10001);
+        cmd.Parameters.Add(id);
+
+        (cmd as MySqlConnector.MySqlCommand)?.Prepare();
+
+        return cmd;
+    }
 
-        async Task<World> ReadSingleRow(DbConnection connection, DbCommand cmd)
+    public async Task<World[]> LoadMultipleQueriesRows(int count)
+    {
+        var result = new World[count];
+
+        using (var db = _dbProviderFactory.CreateConnection())
         {
-            using (var rdr = await cmd.ExecuteReaderAsync(CommandBehavior.SingleRow))
+            db.ConnectionString = _connectionString;
+            await db.OpenAsync();
+            using var cmd = CreateReadCommand(db);
+            for (int i = 0; i < count; i++)
             {
-                await rdr.ReadAsync();
-
-                return new World
-                {
-                    Id = rdr.GetInt32(0),
-                    RandomNumber = rdr.GetInt32(1)
-                };
+                result[i] = await ReadSingleRow(db, cmd);
+                cmd.Parameters["@Id"].Value = _random.Next(1, 10001);
             }
         }
 
-        DbCommand CreateReadCommand(DbConnection connection)
-        {
-            var cmd = connection.CreateCommand();
-            cmd.CommandText = "SELECT id, randomnumber FROM world WHERE id = @Id";
-            var id = cmd.CreateParameter();
-            id.ParameterName = "@Id";
-            id.DbType = DbType.Int32;
-            id.Value = _random.Next(1, 10001);
-            cmd.Parameters.Add(id);
-
-            (cmd as MySqlConnector.MySqlCommand)?.Prepare();
+        return result;
+    }
 
-            return cmd;
+    public async Task<World[]> LoadMultipleUpdatesRows(int count)
+    {
+        using var db = _dbProviderFactory.CreateConnection();
+        db.ConnectionString = _connectionString;
+        await db.OpenAsync();
+
+        using var updateCmd = db.CreateCommand();
+        using var queryCmd = CreateReadCommand(db);
+        var results = new World[count];
+        for (int i = 0; i < count; i++)
+        {
+            results[i] = await ReadSingleRow(db, queryCmd);
+            queryCmd.Parameters["@Id"].Value = _random.Next(1, 10001);
         }
 
-        public async Task<World[]> LoadMultipleQueriesRows(int count)
+        updateCmd.CommandText = BatchUpdateString.Query(count);
+
+        for (int i = 0; i < count; i++)
         {
-            var result = new World[count];
+            var id = updateCmd.CreateParameter();
+            id.ParameterName = $"@Id_{i}";
+            id.DbType = DbType.Int32;
+            updateCmd.Parameters.Add(id);
 
-            using (var db = _dbProviderFactory.CreateConnection())
-            {
-                db.ConnectionString = _connectionString;
-                await db.OpenAsync();
-                using (var cmd = CreateReadCommand(db))
-                {
-                    for (int i = 0; i < count; i++)
-                    {
-                        result[i] = await ReadSingleRow(db, cmd);
-                        cmd.Parameters["@Id"].Value = _random.Next(1, 10001);
-                    }
-                }
-            }
+            var random = updateCmd.CreateParameter();
+            random.ParameterName = $"@Random_{i}";
+            random.DbType = DbType.Int32;
+            updateCmd.Parameters.Add(random);
 
-            return result;
+            var randomNumber = _random.Next(1, 10001);
+            id.Value = results[i].Id;
+            random.Value = randomNumber;
+            results[i].RandomNumber = randomNumber;
         }
 
-        public async Task<World[]> LoadMultipleUpdatesRows(int count)
-        {
-            using (var db = _dbProviderFactory.CreateConnection())
-            {
-                db.ConnectionString = _connectionString;
-                await db.OpenAsync();
+        await updateCmd.ExecuteNonQueryAsync();
+        return results;
+    }
 
-                using (var updateCmd = db.CreateCommand())
-                using (var queryCmd = CreateReadCommand(db))
-                {
-                    var results = new World[count];
-                    for (int i = 0; i < count; i++)
-                    {
-                        results[i] = await ReadSingleRow(db, queryCmd);
-                        queryCmd.Parameters["@Id"].Value = _random.Next(1, 10001);
-                    }
-
-                    updateCmd.CommandText = BatchUpdateString.Query(count);
-
-                    for (int i = 0; i < count; i++)
-                    {
-                        var id = updateCmd.CreateParameter();
-                        id.ParameterName = $"@Id_{i}";
-                        id.DbType = DbType.Int32;
-                        updateCmd.Parameters.Add(id);
-
-                        var random = updateCmd.CreateParameter();
-                        random.ParameterName = $"@Random_{i}";
-                        random.DbType = DbType.Int32;
-                        updateCmd.Parameters.Add(random);
-
-                        var randomNumber = _random.Next(1, 10001);
-                        id.Value = results[i].Id;
-                        random.Value = randomNumber;
-                        results[i].RandomNumber = randomNumber;
-                    }
-
-                    await updateCmd.ExecuteNonQueryAsync();
-                    return results;
-                }
-            }
-        }
+    public async Task<List<Fortune>> LoadFortunesRows()
+    {
+        var result = new List<Fortune>();
 
-        public async Task<List<Fortune>> LoadFortunesRows()
+        using (var db = _dbProviderFactory.CreateConnection())
+        using (var cmd = db.CreateCommand())
         {
-            var result = new List<Fortune>();
-
-            using (var db = _dbProviderFactory.CreateConnection())
-            using (var cmd = db.CreateCommand())
-            {
-                cmd.CommandText = "SELECT id, message FROM fortune";
+            cmd.CommandText = "SELECT id, message FROM fortune";
 
-                db.ConnectionString = _connectionString;
-                await db.OpenAsync();
+            db.ConnectionString = _connectionString;
+            await db.OpenAsync();
 
-                (cmd as MySqlConnector.MySqlCommand)?.Prepare();
+            (cmd as MySqlConnector.MySqlCommand)?.Prepare();
 
-                using (var rdr = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection))
+            using var rdr = await cmd.ExecuteReaderAsync(CommandBehavior.CloseConnection);
+            while (await rdr.ReadAsync())
+            {
+                result.Add(new Fortune
                 {
-                    while (await rdr.ReadAsync())
-                    {
-                        result.Add(new Fortune
-                        {
-                            Id = rdr.GetInt32(0),
-                            Message = rdr.GetString(1)
-                        });
-                    }
-                }
+                    Id = rdr.GetInt32(0),
+                    Message = rdr.GetString(1)
+                });
             }
+        }
 
-            result.Add(new Fortune { Message = "Additional fortune added at request time." });
-            result.Sort();
+        result.Add(new Fortune { Message = "Additional fortune added at request time." });
+        result.Sort();
 
-            return result;
-        }
+        return result;
     }
 }

+ 36 - 38
frameworks/CSharp/aspnetcore/Benchmarks/Data/StringBuilderCache.cs

@@ -1,59 +1,57 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
 using System.Text;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+internal static class StringBuilderCache
 {
-    internal static class StringBuilderCache
-    {
-        private const int DefaultCapacity = 1386;
-        private const int MaxBuilderSize = DefaultCapacity * 3;
+    private const int DefaultCapacity = 1386;
+    private const int MaxBuilderSize = DefaultCapacity * 3;
 
-        [ThreadStatic]
-        private static StringBuilder t_cachedInstance;
+    [ThreadStatic]
+    private static StringBuilder t_cachedInstance;
 
-        /// <summary>Get a StringBuilder for the specified capacity.</summary>
-        /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks>
-        public static StringBuilder Acquire(int capacity = DefaultCapacity)
+    /// <summary>Get a StringBuilder for the specified capacity.</summary>
+    /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks>
+    public static StringBuilder Acquire(int capacity = DefaultCapacity)
+    {
+        if (capacity <= MaxBuilderSize)
         {
-            if (capacity <= MaxBuilderSize)
+            StringBuilder sb = t_cachedInstance;
+            if (capacity < DefaultCapacity)
             {
-                StringBuilder sb = t_cachedInstance;
-                if (capacity < DefaultCapacity)
-                {
-                    capacity = DefaultCapacity;
-                }
+                capacity = DefaultCapacity;
+            }
 
-                if (sb != null)
+            if (sb != null)
+            {
+                // Avoid stringbuilder block fragmentation by getting a new StringBuilder
+                // when the requested size is larger than the current capacity
+                if (capacity <= sb.Capacity)
                 {
-                    // Avoid stringbuilder block fragmentation by getting a new StringBuilder
-                    // when the requested size is larger than the current capacity
-                    if (capacity <= sb.Capacity)
-                    {
-                        t_cachedInstance = null;
-                        sb.Clear();
-                        return sb;
-                    }
+                    t_cachedInstance = null;
+                    sb.Clear();
+                    return sb;
                 }
             }
-            return new StringBuilder(capacity);
         }
+        return new StringBuilder(capacity);
+    }
 
-        public static void Release(StringBuilder sb)
+    public static void Release(StringBuilder sb)
+    {
+        if (sb.Capacity <= MaxBuilderSize)
         {
-            if (sb.Capacity <= MaxBuilderSize)
-            {
-                t_cachedInstance = sb;
-            }
+            t_cachedInstance = sb;
         }
+    }
 
-        public static string GetStringAndRelease(StringBuilder sb)
-        {
-            string result = sb.ToString();
-            Release(sb);
-            return result;
-        }
+    public static string GetStringAndRelease(StringBuilder sb)
+    {
+        string result = sb.ToString();
+        Release(sb);
+        return result;
     }
 }

+ 8 - 9
frameworks/CSharp/aspnetcore/Benchmarks/Data/World.cs

@@ -3,15 +3,14 @@
 
 using System.ComponentModel.DataAnnotations.Schema;
 
-namespace Benchmarks.Data
+namespace Benchmarks.Data;
+
+[Table("world")]
+public class World
 {
-    [Table("world")]
-    public class World
-    {
-        [Column("id")]
-        public int Id { get; set; }
+    [Column("id")]
+    public int Id { get; set; }
 
-        [Column("randomnumber")]
-        public int RandomNumber { get; set; }
-    }
+    [Column("randomnumber")]
+    public int RandomNumber { get; set; }
 }

+ 25 - 31
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/FortunesDapperMiddleware.cs

@@ -1,51 +1,45 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Encodings.Web;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class FortunesDapperMiddleware
 {
-    public class FortunesDapperMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbFortunesDapper));
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbFortunesDapper));
 
-        private readonly RequestDelegate _next;
-        private readonly HtmlEncoder _htmlEncoder;
+    private readonly RequestDelegate _next;
+    private readonly HtmlEncoder _htmlEncoder;
 
-        public FortunesDapperMiddleware(RequestDelegate next, HtmlEncoder htmlEncoder)
-        {
-            _next = next;
-            _htmlEncoder = htmlEncoder;
-        }
+    public FortunesDapperMiddleware(RequestDelegate next, HtmlEncoder htmlEncoder)
+    {
+        _next = next;
+        _htmlEncoder = htmlEncoder;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var db = httpContext.RequestServices.GetService<DapperDb>();
-                var rows = await db.LoadFortunesRows();
+            var db = httpContext.RequestServices.GetService<DapperDb>();
+            var rows = await db.LoadFortunesRows();
 
-                await MiddlewareHelpers.RenderFortunesHtml(rows, httpContext, _htmlEncoder);
+            await MiddlewareHelpers.RenderFortunesHtml(rows, httpContext, _htmlEncoder);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class FortunesDapperMiddlewareExtensions
+public static class FortunesDapperMiddlewareExtensions
+{
+    public static IApplicationBuilder UseFortunesDapper(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseFortunesDapper(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<FortunesDapperMiddleware>();
-        }
+        return builder.UseMiddleware<FortunesDapperMiddleware>();
     }
 }

+ 25 - 31
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/FortunesEfMiddleware.cs

@@ -1,51 +1,45 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Encodings.Web;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class FortunesEfMiddleware
 {
-    public class FortunesEfMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbFortunesEf));
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbFortunesEf));
 
-        private readonly RequestDelegate _next;
-        private readonly HtmlEncoder _htmlEncoder;
+    private readonly RequestDelegate _next;
+    private readonly HtmlEncoder _htmlEncoder;
 
-        public FortunesEfMiddleware(RequestDelegate next, HtmlEncoder htmlEncoder)
-        {
-            _next = next;
-            _htmlEncoder = htmlEncoder;
-        }
+    public FortunesEfMiddleware(RequestDelegate next, HtmlEncoder htmlEncoder)
+    {
+        _next = next;
+        _htmlEncoder = htmlEncoder;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var db = httpContext.RequestServices.GetService<EfDb>();
-                var rows = await db.LoadFortunesRows();
+            var db = httpContext.RequestServices.GetService<EfDb>();
+            var rows = await db.LoadFortunesRows();
 
-                await MiddlewareHelpers.RenderFortunesHtml(rows, httpContext, _htmlEncoder);
+            await MiddlewareHelpers.RenderFortunesHtml(rows, httpContext, _htmlEncoder);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class FortunesEfMiddlewareExtensions
+public static class FortunesEfMiddlewareExtensions
+{
+    public static IApplicationBuilder UseFortunesEf(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseFortunesEf(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<FortunesEfMiddleware>();
-        }
+        return builder.UseMiddleware<FortunesEfMiddleware>();
     }
 }

+ 25 - 31
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/FortunesRawMiddleware.cs

@@ -1,51 +1,45 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Encodings.Web;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class FortunesRawMiddleware
 {
-    public class FortunesRawMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbFortunesRaw));
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbFortunesRaw));
 
-        private readonly RequestDelegate _next;
-        private readonly HtmlEncoder _htmlEncoder;
+    private readonly RequestDelegate _next;
+    private readonly HtmlEncoder _htmlEncoder;
 
-        public FortunesRawMiddleware(RequestDelegate next, HtmlEncoder htmlEncoder)
-        {
-            _next = next;
-            _htmlEncoder = htmlEncoder;
-        }
+    public FortunesRawMiddleware(RequestDelegate next, HtmlEncoder htmlEncoder)
+    {
+        _next = next;
+        _htmlEncoder = htmlEncoder;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var db = httpContext.RequestServices.GetService<RawDb>();
-                var rows = await db.LoadFortunesRows();
+            var db = httpContext.RequestServices.GetService<RawDb>();
+            var rows = await db.LoadFortunesRows();
 
-                await MiddlewareHelpers.RenderFortunesHtml(rows, httpContext, _htmlEncoder);
+            await MiddlewareHelpers.RenderFortunesHtml(rows, httpContext, _htmlEncoder);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class FortunesRawMiddlewareExtensions
+public static class FortunesRawMiddlewareExtensions
+{
+    public static IApplicationBuilder UseFortunesRaw(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseFortunesRaw(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<FortunesRawMiddleware>();
-        }
+        return builder.UseMiddleware<FortunesRawMiddleware>();
     }
 }

+ 28 - 37
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/JsonMiddleware.cs

@@ -1,56 +1,47 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using System.IO;
-using System.Text;
 using System.Text.Json;
-using System.Text.Json.Serialization;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
 
-namespace Benchmarks.Middleware
-{
-    public class JsonMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.Json));
-        private static readonly UTF8Encoding _encoding = new UTF8Encoding(false);
-        private const int _bufferSize = 27;
-
-        private readonly RequestDelegate _next;
+namespace Benchmarks.Middleware;
 
-        public JsonMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
-
-        public Task Invoke(HttpContext httpContext)
-        {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                httpContext.Response.StatusCode = 200;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = _bufferSize;
+public class JsonMiddleware
+{
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.Json));
+    private const int _bufferSize = 27;
 
-                return JsonSerializer.SerializeAsync<JsonMessage>(httpContext.Response.Body, new JsonMessage { message = "Hello, World!" });
-            }
+    private readonly RequestDelegate _next;
 
-            return _next(httpContext);
-        }
+    public JsonMiddleware(RequestDelegate next)
+    {
+        _next = next;
     }
 
-    public static class JsonMiddlewareExtensions
+    public Task Invoke(HttpContext httpContext)
     {
-        public static IApplicationBuilder UseJson(this IApplicationBuilder builder)
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            return builder.UseMiddleware<JsonMiddleware>();
+            httpContext.Response.StatusCode = 200;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = _bufferSize;
+
+            return JsonSerializer.SerializeAsync<JsonMessage>(httpContext.Response.Body, new JsonMessage { message = "Hello, World!" });
         }
+
+        return _next(httpContext);
     }
+}
 
-    public struct JsonMessage
+public static class JsonMiddlewareExtensions
+{
+    public static IApplicationBuilder UseJson(this IApplicationBuilder builder)
     {
-        public string message { get; set; }
+        return builder.UseMiddleware<JsonMiddleware>();
     }
 }
+
+public struct JsonMessage
+{
+    public string message { get; set; }
+}

+ 35 - 39
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MiddlewareHelpers.cs

@@ -1,56 +1,52 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System.Collections.Generic;
 using System.Globalization;
 using System.Text;
 using System.Text.Encodings.Web;
-using System.Threading.Tasks;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Http;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public static class MiddlewareHelpers
 {
-    public static class MiddlewareHelpers
+    public static int GetMultipleQueriesQueryCount(HttpContext httpContext)
     {
-        public static int GetMultipleQueriesQueryCount(HttpContext httpContext)
+        var queries = 1;
+        var queriesRaw = httpContext.Request.Query["queries"];
+
+        if (queriesRaw.Count == 1)
         {
-            var queries = 1;
-            var queriesRaw = httpContext.Request.Query["queries"];
-
-            if (queriesRaw.Count == 1)
-            {
-                int.TryParse(queriesRaw, out queries);
-            }
-
-            return queries > 500
-                ? 500
-                : queries > 0
-                    ? queries
-                    : 1;
+            int.TryParse(queriesRaw, out queries);
         }
 
-        public static Task RenderFortunesHtml(IEnumerable<Fortune> model, HttpContext httpContext, HtmlEncoder htmlEncoder)
+        return queries > 500
+            ? 500
+            : queries > 0
+                ? queries
+                : 1;
+    }
+
+    public static Task RenderFortunesHtml(IEnumerable<Fortune> model, HttpContext httpContext, HtmlEncoder htmlEncoder)
+    {
+        httpContext.Response.StatusCode = StatusCodes.Status200OK;
+        httpContext.Response.ContentType = "text/html; charset=UTF-8";
+
+        var sb = StringBuilderCache.Acquire();
+        sb.Append("<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>");
+        foreach (var item in model)
         {
-            httpContext.Response.StatusCode = StatusCodes.Status200OK;
-            httpContext.Response.ContentType = "text/html; charset=UTF-8";
-
-            var sb = StringBuilderCache.Acquire();
-            sb.Append("<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>");
-            foreach (var item in model)
-            {
-                sb.Append("<tr><td>");
-                sb.Append(item.Id.ToString(CultureInfo.InvariantCulture));
-                sb.Append("</td><td>");
-                sb.Append(htmlEncoder.Encode(item.Message));
-                sb.Append("</td></tr>");
-            }
-
-            sb.Append("</table></body></html>");
-            var response = StringBuilderCache.GetStringAndRelease(sb);
-            // fortunes includes multibyte characters so response.Length is incorrect
-            httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(response);
-            return httpContext.Response.WriteAsync(response);
+            sb.Append("<tr><td>");
+            sb.Append(item.Id.ToString(CultureInfo.InvariantCulture));
+            sb.Append("</td><td>");
+            sb.Append(htmlEncoder.Encode(item.Message));
+            sb.Append("</td></tr>");
         }
+
+        sb.Append("</table></body></html>");
+        var response = StringBuilderCache.GetStringAndRelease(sb);
+        // fortunes includes multibyte characters so response.Length is incorrect
+        httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(response);
+        return httpContext.Response.WriteAsync(response);
     }
 }

+ 29 - 35
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleQueriesDapperMiddleware.cs

@@ -1,58 +1,52 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class MultipleQueriesDapperMiddleware
 {
-    public class MultipleQueriesDapperMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiQueryDapper));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbMultiQueryDapper));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
 
-        private readonly RequestDelegate _next;
+    private readonly RequestDelegate _next;
 
-        public MultipleQueriesDapperMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public MultipleQueriesDapperMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
+            var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
 
-                var db = httpContext.RequestServices.GetService<DapperDb>();
-                var rows = await db.LoadMultipleQueriesRows(count);
+            var db = httpContext.RequestServices.GetService<DapperDb>();
+            var rows = await db.LoadMultipleQueriesRows(count);
 
-                var result = JsonSerializer.Serialize(rows, _serializerOptions);
+            var result = JsonSerializer.Serialize(rows, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class MultipleQueriesDapperMiddlewareExtensions
+public static class MultipleQueriesDapperMiddlewareExtensions
+{
+    public static IApplicationBuilder UseMultipleQueriesDapper(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseMultipleQueriesDapper(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<MultipleQueriesDapperMiddleware>();
-        }
+        return builder.UseMiddleware<MultipleQueriesDapperMiddleware>();
     }
 }

+ 29 - 35
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleQueriesEfMiddleware.cs

@@ -1,58 +1,52 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class MultipleQueriesEfMiddleware
 {
-    public class MultipleQueriesEfMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiQueryEf));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbMultiQueryEf));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
 
-        private readonly RequestDelegate _next;
+    private readonly RequestDelegate _next;
 
-        public MultipleQueriesEfMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public MultipleQueriesEfMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
+            var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
 
-                var db = httpContext.RequestServices.GetService<EfDb>();
-                var rows = await db.LoadMultipleQueriesRows(count);
+            var db = httpContext.RequestServices.GetService<EfDb>();
+            var rows = await db.LoadMultipleQueriesRows(count);
 
-                var result = JsonSerializer.Serialize(rows, _serializerOptions);
+            var result = JsonSerializer.Serialize(rows, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class MultipleQueriesEfMiddlewareExtensions
+public static class MultipleQueriesEfMiddlewareExtensions
+{
+    public static IApplicationBuilder UseMultipleQueriesEf(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseMultipleQueriesEf(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<MultipleQueriesEfMiddleware>();
-        }
+        return builder.UseMiddleware<MultipleQueriesEfMiddleware>();
     }
 }

+ 29 - 35
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleQueriesRawMiddleware.cs

@@ -1,58 +1,52 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class MultipleQueriesRawMiddleware
 {
-    public class MultipleQueriesRawMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiQueryRaw));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbMultiQueryRaw));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
 
-        private readonly RequestDelegate _next;
+    private readonly RequestDelegate _next;
 
-        public MultipleQueriesRawMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public MultipleQueriesRawMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
+            var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
 
-                var db = httpContext.RequestServices.GetService<RawDb>();
-                var rows = await db.LoadMultipleQueriesRows(count);
+            var db = httpContext.RequestServices.GetService<RawDb>();
+            var rows = await db.LoadMultipleQueriesRows(count);
 
-                var result = JsonSerializer.Serialize(rows, _serializerOptions);
+            var result = JsonSerializer.Serialize(rows, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class MultipleQueriesRawMiddlewareExtensions
+public static class MultipleQueriesRawMiddlewareExtensions
+{
+    public static IApplicationBuilder UseMultipleQueriesRaw(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseMultipleQueriesRaw(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<MultipleQueriesRawMiddleware>();
-        }
+        return builder.UseMiddleware<MultipleQueriesRawMiddleware>();
     }
 }

+ 29 - 35
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesDapperMiddleware.cs

@@ -1,57 +1,51 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class MultipleUpdatesDapperMiddleware
 {
-    public class MultipleUpdatesDapperMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiUpdateDapper));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
-        private readonly RequestDelegate _next;
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbMultiUpdateDapper));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private readonly RequestDelegate _next;
 
-        public MultipleUpdatesDapperMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public MultipleUpdatesDapperMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
+            var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
 
-                var db = httpContext.RequestServices.GetService<DapperDb>();
-                var rows = await db.LoadMultipleUpdatesRows(count);
+            var db = httpContext.RequestServices.GetService<DapperDb>();
+            var rows = await db.LoadMultipleUpdatesRows(count);
 
-                var result = JsonSerializer.Serialize(rows, _serializerOptions);
+            var result = JsonSerializer.Serialize(rows, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class MultipleUpdatesDapperMiddlewareExtensions
+public static class MultipleUpdatesDapperMiddlewareExtensions
+{
+    public static IApplicationBuilder UseMultipleUpdatesDapper(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseMultipleUpdatesDapper(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<MultipleUpdatesDapperMiddleware>();
-        }
+        return builder.UseMiddleware<MultipleUpdatesDapperMiddleware>();
     }
 }

+ 29 - 35
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesEfMiddleware.cs

@@ -1,57 +1,51 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class MultipleUpdatesEfMiddleware
 {
-    public class MultipleUpdatesEfMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiUpdateEf));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
-        private readonly RequestDelegate _next;
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbMultiUpdateEf));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private readonly RequestDelegate _next;
 
-        public MultipleUpdatesEfMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public MultipleUpdatesEfMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
+            var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
 
-                var db = httpContext.RequestServices.GetService<EfDb>();
-                var rows = await db.LoadMultipleUpdatesRows(count);
+            var db = httpContext.RequestServices.GetService<EfDb>();
+            var rows = await db.LoadMultipleUpdatesRows(count);
 
-                var result = JsonSerializer.Serialize(rows, _serializerOptions);
+            var result = JsonSerializer.Serialize(rows, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class MultipleUpdatesEfMiddlewareExtensions
+public static class MultipleUpdatesEfMiddlewareExtensions
+{
+    public static IApplicationBuilder UseMultipleUpdatesEf(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseMultipleUpdatesEf(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<MultipleUpdatesEfMiddleware>();
-        }
+        return builder.UseMiddleware<MultipleUpdatesEfMiddleware>();
     }
 }

+ 29 - 35
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/MultipleUpdatesRawMiddleware.cs

@@ -1,58 +1,52 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class MultipleUpdatesRawMiddleware
 {
-    public class MultipleUpdatesRawMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbMultiUpdateRaw));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbMultiUpdateRaw));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
 
-        private readonly RequestDelegate _next;
+    private readonly RequestDelegate _next;
 
-        public MultipleUpdatesRawMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public MultipleUpdatesRawMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
+            var count = MiddlewareHelpers.GetMultipleQueriesQueryCount(httpContext);
 
-                var db = httpContext.RequestServices.GetService<RawDb>();
-                var rows = await db.LoadMultipleUpdatesRows(count);
+            var db = httpContext.RequestServices.GetService<RawDb>();
+            var rows = await db.LoadMultipleUpdatesRows(count);
 
-                var result = JsonSerializer.Serialize(rows, _serializerOptions);
+            var result = JsonSerializer.Serialize(rows, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class MultipleUpdatesRawMiddlewareExtensions
+public static class MultipleUpdatesRawMiddlewareExtensions
+{
+    public static IApplicationBuilder UseMultipleUpdatesRaw(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseMultipleUpdatesRaw(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<MultipleUpdatesRawMiddleware>();
-        }
+        return builder.UseMiddleware<MultipleUpdatesRawMiddleware>();
     }
 }

+ 29 - 34
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/PlaintextMiddleware.cs

@@ -1,52 +1,47 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class PlaintextMiddleware
 {
-    public class PlaintextMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.Plaintext));
-        private static readonly byte[] _helloWorldPayload = Encoding.UTF8.GetBytes("Hello, World!");
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.Plaintext));
+    private static readonly byte[] _helloWorldPayload = Encoding.UTF8.GetBytes("Hello, World!");
 
-        private readonly RequestDelegate _next;
+    private readonly RequestDelegate _next;
 
-        public PlaintextMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public PlaintextMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public Task Invoke(HttpContext httpContext)
+    public Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                return WriteResponse(httpContext.Response);
-            }
-
-            return _next(httpContext);
+            return WriteResponse(httpContext.Response);
         }
 
-        public static Task WriteResponse(HttpResponse response)
-        {
-            var payloadLength = _helloWorldPayload.Length;
-            response.StatusCode = 200;
-            response.ContentType = "text/plain";
-            response.ContentLength = payloadLength;
-            return response.Body.WriteAsync(_helloWorldPayload, 0, payloadLength);
-        }
+        return _next(httpContext);
     }
 
-    public static class PlaintextMiddlewareExtensions
+    public static Task WriteResponse(HttpResponse response)
     {
-        public static IApplicationBuilder UsePlainText(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<PlaintextMiddleware>();
-        }
+        var payloadLength = _helloWorldPayload.Length;
+        response.StatusCode = 200;
+        response.ContentType = "text/plain";
+        response.ContentLength = payloadLength;
+        return response.Body.WriteAsync(_helloWorldPayload, 0, payloadLength);
+    }
+}
+
+public static class PlaintextMiddlewareExtensions
+{
+    public static IApplicationBuilder UsePlainText(this IApplicationBuilder builder)
+    {
+        return builder.UseMiddleware<PlaintextMiddleware>();
     }
 }

+ 28 - 34
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/SingleQueryDapperMiddleware.cs

@@ -1,56 +1,50 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class SingleQueryDapperMiddleware
 {
-    public class SingleQueryDapperMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbSingleQueryDapper));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbSingleQueryDapper));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
 
-        private readonly RequestDelegate _next;
+    private readonly RequestDelegate _next;
 
-        public SingleQueryDapperMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public SingleQueryDapperMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var db = httpContext.RequestServices.GetService<DapperDb>();
-                var row = await db.LoadSingleQueryRow();
+            var db = httpContext.RequestServices.GetService<DapperDb>();
+            var row = await db.LoadSingleQueryRow();
 
-                var result = JsonSerializer.Serialize(row, _serializerOptions);
+            var result = JsonSerializer.Serialize(row, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class SingleQueryDapperMiddlewareExtensions
+public static class SingleQueryDapperMiddlewareExtensions
+{
+    public static IApplicationBuilder UseSingleQueryDapper(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseSingleQueryDapper(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<SingleQueryDapperMiddleware>();
-        }
+        return builder.UseMiddleware<SingleQueryDapperMiddleware>();
     }
 }

+ 28 - 34
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/SingleQueryEfMiddleware.cs

@@ -1,55 +1,49 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class SingleQueryEfMiddleware
 {
-    public class SingleQueryEfMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbSingleQueryEf));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbSingleQueryEf));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
 
-        private readonly RequestDelegate _next;
+    private readonly RequestDelegate _next;
 
-        public SingleQueryEfMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public SingleQueryEfMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var db = httpContext.RequestServices.GetService<EfDb>();
-                var row = await db.LoadSingleQueryRow();
-                var result = JsonSerializer.Serialize(row, _serializerOptions);
+            var db = httpContext.RequestServices.GetService<EfDb>();
+            var row = await db.LoadSingleQueryRow();
+            var result = JsonSerializer.Serialize(row, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class SingleQueryEfMiddlewareExtensions
+public static class SingleQueryEfMiddlewareExtensions
+{
+    public static IApplicationBuilder UseSingleQueryEf(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseSingleQueryEf(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<SingleQueryEfMiddleware>();
-        }
+        return builder.UseMiddleware<SingleQueryEfMiddleware>();
     }
 }

+ 28 - 34
frameworks/CSharp/aspnetcore/Benchmarks/Middleware/SingleQueryRawMiddleware.cs

@@ -1,56 +1,50 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text.Json;
-using System.Threading.Tasks;
 using Benchmarks.Configuration;
 using Benchmarks.Data;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.DependencyInjection;
 
-namespace Benchmarks.Middleware
+namespace Benchmarks.Middleware;
+
+public class SingleQueryRawMiddleware
 {
-    public class SingleQueryRawMiddleware
-    {
-        private static readonly PathString _path = new PathString(Scenarios.GetPath(s => s.DbSingleQueryRaw));
-        private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
+    private static readonly PathString _path = new(Scenarios.GetPath(s => s.DbSingleQueryRaw));
+    private static readonly JsonSerializerOptions _serializerOptions = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
 
-        private readonly RequestDelegate _next;
+    private readonly RequestDelegate _next;
 
-        public SingleQueryRawMiddleware(RequestDelegate next)
-        {
-            _next = next;
-        }
+    public SingleQueryRawMiddleware(RequestDelegate next)
+    {
+        _next = next;
+    }
 
-        public async Task Invoke(HttpContext httpContext)
+    public async Task Invoke(HttpContext httpContext)
+    {
+        if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
         {
-            if (httpContext.Request.Path.StartsWithSegments(_path, StringComparison.Ordinal))
-            {
-                var db = httpContext.RequestServices.GetService<RawDb>();
-                var row = await db.LoadSingleQueryRow();
+            var db = httpContext.RequestServices.GetService<RawDb>();
+            var row = await db.LoadSingleQueryRow();
 
-                var result = JsonSerializer.Serialize(row, _serializerOptions);
+            var result = JsonSerializer.Serialize(row, _serializerOptions);
 
-                httpContext.Response.StatusCode = StatusCodes.Status200OK;
-                httpContext.Response.ContentType = "application/json";
-                httpContext.Response.ContentLength = result.Length;
+            httpContext.Response.StatusCode = StatusCodes.Status200OK;
+            httpContext.Response.ContentType = "application/json";
+            httpContext.Response.ContentLength = result.Length;
 
-                await httpContext.Response.WriteAsync(result);
+            await httpContext.Response.WriteAsync(result);
 
-                return;
-            }
-
-            await _next(httpContext);
+            return;
         }
+
+        await _next(httpContext);
     }
+}
 
-    public static class SingleQueryRawMiddlewareExtensions
+public static class SingleQueryRawMiddlewareExtensions
+{
+    public static IApplicationBuilder UseSingleQueryRaw(this IApplicationBuilder builder)
     {
-        public static IApplicationBuilder UseSingleQueryRaw(this IApplicationBuilder builder)
-        {
-            return builder.UseMiddleware<SingleQueryRawMiddleware>();
-        }
+        return builder.UseMiddleware<SingleQueryRawMiddleware>();
     }
 }

+ 45 - 54
frameworks/CSharp/aspnetcore/Benchmarks/Program.cs

@@ -1,77 +1,68 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using System.IO;
 using System.Reflection;
 using System.Runtime;
-using System.Threading;
 using Benchmarks.Configuration;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Logging;
 
-namespace Benchmarks
+namespace Benchmarks;
+
+public class Program
 {
-    public class Program
-    {
-        public static string[] Args;
+    public static string[] Args;
 
-        public static void Main(string[] args)
-        {
-            Args = args;
+    public static void Main(string[] args)
+    {
+        Args = args;
 
-            Console.WriteLine();
-            Console.WriteLine("ASP.NET Core Benchmarks");
-            Console.WriteLine("-----------------------");
+        Console.WriteLine();
+        Console.WriteLine("ASP.NET Core Benchmarks");
+        Console.WriteLine("-----------------------");
 
-            Console.WriteLine($"Current directory: {Directory.GetCurrentDirectory()}");
-            Console.WriteLine($"WebHostBuilder loading from: {typeof(WebHostBuilder).GetTypeInfo().Assembly.Location}");
+        Console.WriteLine($"Current directory: {Directory.GetCurrentDirectory()}");
+        Console.WriteLine($"WebHostBuilder loading from: {typeof(WebHostBuilder).GetTypeInfo().Assembly.Location}");
 
-            var config = new ConfigurationBuilder()
-                .AddJsonFile("hosting.json", optional: true)
-                .AddEnvironmentVariables(prefix: "ASPNETCORE_")
-                .AddCommandLine(args)
-                .Build();
+        var config = new ConfigurationBuilder()
+            .AddJsonFile("hosting.json", optional: true)
+            .AddEnvironmentVariables(prefix: "ASPNETCORE_")
+            .AddCommandLine(args)
+            .Build();
 
-            var webHostBuilder = new WebHostBuilder()
-                .UseContentRoot(Directory.GetCurrentDirectory())
-                .UseConfiguration(config)
-                .UseStartup<Startup>()
-                .ConfigureServices(services => services
-                    .AddSingleton(new ConsoleArgs(args))
-                    .AddSingleton<IScenariosConfiguration, ConsoleHostScenariosConfiguration>()
-                    .AddSingleton<Scenarios>()
-                )
-                .UseDefaultServiceProvider(
-                    (context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment())
-                .UseKestrel();
+        var webHostBuilder = new WebHostBuilder()
+            .UseContentRoot(Directory.GetCurrentDirectory())
+            .UseConfiguration(config)
+            .UseStartup<Startup>()
+            .ConfigureServices(services => services
+                .AddSingleton(new ConsoleArgs(args))
+                .AddSingleton<IScenariosConfiguration, ConsoleHostScenariosConfiguration>()
+                .AddSingleton<Scenarios>()
+            )
+            .UseDefaultServiceProvider(
+                (context, options) => options.ValidateScopes = context.HostingEnvironment.IsDevelopment())
+            .UseKestrel();
 
-            var threadCount = GetThreadCount(config);
+        var threadCount = GetThreadCount(config);
 
-            webHostBuilder.UseSockets(x =>
+        webHostBuilder.UseSockets(x =>
+        {
+            if (threadCount > 0)
             {
-                if (threadCount > 0)
-                {
-                    x.IOQueueCount = threadCount;
-                }
+                x.IOQueueCount = threadCount;
+            }
 
-                Console.WriteLine($"Using Sockets with {x.IOQueueCount} threads");
-            });
+            Console.WriteLine($"Using Sockets with {x.IOQueueCount} threads");
+        });
 
-            var webHost = webHostBuilder.Build();
+        var webHost = webHostBuilder.Build();
 
-            Console.WriteLine($"Server GC is currently {(GCSettings.IsServerGC ? "ENABLED" : "DISABLED")}");
+        Console.WriteLine($"Server GC is currently {(GCSettings.IsServerGC ? "ENABLED" : "DISABLED")}");
 
-            webHost.Run();
-        }
+        webHost.Run();
+    }
 
-        private static int GetThreadCount(IConfigurationRoot config)
-        {
-            var threadCountValue = config["threadCount"];
-            return threadCountValue == null ? -1 : int.Parse(threadCountValue);
-        }
+    private static int GetThreadCount(IConfigurationRoot config)
+    {
+        var threadCountValue = config["threadCount"];
+        return threadCountValue == null ? -1 : int.Parse(threadCountValue);
     }
 }

+ 149 - 155
frameworks/CSharp/aspnetcore/Benchmarks/Startup.cs

@@ -4,211 +4,205 @@
 using Benchmarks.Configuration;
 using Benchmarks.Data;
 using Benchmarks.Middleware;
-using Microsoft.AspNetCore.Builder;
-using Microsoft.AspNetCore.Hosting;
 using Microsoft.EntityFrameworkCore;
-using Microsoft.Extensions.Configuration;
-using Microsoft.Extensions.DependencyInjection;
 using MySqlConnector;
 using Npgsql;
-using System;
 using System.Data.Common;
 using System.Text.Encodings.Web;
 using System.Text.Unicode;
 using Microsoft.EntityFrameworkCore.Storage;
 
-namespace Benchmarks
+namespace Benchmarks;
+
+public class Startup
 {
-    public class Startup
+    public Startup(IWebHostEnvironment hostingEnv, Scenarios scenarios)
     {
-        public Startup(IWebHostEnvironment hostingEnv, Scenarios scenarios)
-        {
-            // Set up configuration sources.
-            var builder = new ConfigurationBuilder()
-                .SetBasePath(hostingEnv.ContentRootPath)
-                .AddJsonFile("appsettings.json")
-                .AddJsonFile($"appsettings.{hostingEnv.EnvironmentName}.json", optional: true)
-                .AddEnvironmentVariables()
-                .AddCommandLine(Program.Args)
-                ;
-
-            Configuration = builder.Build();
-
-            Scenarios = scenarios;
-        }
-
-        public IConfigurationRoot Configuration { get; set; }
+        // Set up configuration sources.
+        var builder = new ConfigurationBuilder()
+            .SetBasePath(hostingEnv.ContentRootPath)
+            .AddJsonFile("appsettings.json")
+            .AddJsonFile($"appsettings.{hostingEnv.EnvironmentName}.json", optional: true)
+            .AddEnvironmentVariables()
+            .AddCommandLine(Program.Args)
+            ;
+
+        Configuration = builder.Build();
+
+        Scenarios = scenarios;
+    }
 
-        public Scenarios Scenarios { get; }
+    public IConfigurationRoot Configuration { get; set; }
 
-        public void ConfigureServices(IServiceCollection services)
-        {
-            services.Configure<AppSettings>(Configuration);
+    public Scenarios Scenarios { get; }
 
-            // We re-register the Scenarios as an instance singleton here to avoid it being created again due to the
-            // registration done in Program.Main
-            services.AddSingleton(Scenarios);
+    public void ConfigureServices(IServiceCollection services)
+    {
+        services.Configure<AppSettings>(Configuration);
 
-            // Common DB services
-            services.AddSingleton<IRandom, DefaultRandom>();
-            services.AddEntityFrameworkSqlServer();
+        // We re-register the Scenarios as an instance singleton here to avoid it being created again due to the
+        // registration done in Program.Main
+        services.AddSingleton(Scenarios);
 
-            var appSettings = Configuration.Get<AppSettings>();
-            BatchUpdateString.DatabaseServer = appSettings.Database;
+        // Common DB services
+        services.AddSingleton<IRandom, DefaultRandom>();
+        services.AddEntityFrameworkSqlServer();
 
-            Console.WriteLine($"Database: {appSettings.Database}");
+        var appSettings = Configuration.Get<AppSettings>();
+        BatchUpdateString.DatabaseServer = appSettings.Database;
 
-            if (appSettings.Database == DatabaseServer.PostgreSql)
-            {
-                if (Scenarios.Any("Ef"))
-                {
-                    services.AddDbContextPool<ApplicationDbContext>(options => options
-                        .UseNpgsql(appSettings.ConnectionString,
-                            o => o.ExecutionStrategy(d => new NonRetryingExecutionStrategy(d)))
-                        .EnableThreadSafetyChecks(false));
-                }
-
-                if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
-                {
-                    services.AddSingleton<DbProviderFactory>(NpgsqlFactory.Instance);
-                }
-            }
-            else if (appSettings.Database == DatabaseServer.MySql)
-            {
-                if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
-                {
-                    services.AddSingleton<DbProviderFactory>(MySqlConnectorFactory.Instance);
-                }
-            }
+        Console.WriteLine($"Database: {appSettings.Database}");
 
+        if (appSettings.Database == DatabaseServer.PostgreSql)
+        {
             if (Scenarios.Any("Ef"))
             {
-                services.AddScoped<EfDb>();
+                services.AddDbContextPool<ApplicationDbContext>(options => options
+                    .UseNpgsql(appSettings.ConnectionString,
+                        o => o.ExecutionStrategy(d => new NonRetryingExecutionStrategy(d)))
+                    .EnableThreadSafetyChecks(false));
             }
 
-            if (Scenarios.Any("Raw"))
+            if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
             {
-                services.AddScoped<RawDb>();
+                services.AddSingleton<DbProviderFactory>(NpgsqlFactory.Instance);
             }
-
-            if (Scenarios.Any("Dapper"))
+        }
+        else if (appSettings.Database == DatabaseServer.MySql)
+        {
+            if (Scenarios.Any("Raw") || Scenarios.Any("Dapper"))
             {
-                services.AddScoped<DapperDb>();
+                services.AddSingleton<DbProviderFactory>(MySqlConnectorFactory.Instance);
             }
+        }
 
-            if (Scenarios.Any("Fortunes"))
-            {
-                var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
-                settings.AllowCharacter('\u2014');  // allow EM DASH through
-                services.AddWebEncoders((options) =>
-                {
-                    options.TextEncoderSettings = settings;
-                });
-            }
+        if (Scenarios.Any("Ef"))
+        {
+            services.AddScoped<EfDb>();
+        }
 
-            if (Scenarios.Any("Mvc"))
-            {
-                var mvcBuilder = services.AddMvcCore();
-
-                if (Scenarios.MvcViews || Scenarios.Any("MvcDbFortunes"))
-                {
-                    mvcBuilder
-                        .AddViews()
-                        .AddRazorViewEngine();
-                }
-            }
+        if (Scenarios.Any("Raw"))
+        {
+            services.AddScoped<RawDb>();
         }
 
-        public void Configure(IApplicationBuilder app)
+        if (Scenarios.Any("Dapper"))
         {
-            if (Scenarios.Plaintext)
-            {
-                app.UsePlainText();
-            }
+            services.AddScoped<DapperDb>();
+        }
 
-            if (Scenarios.Json)
+        if (Scenarios.Any("Fortunes"))
+        {
+            var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
+            settings.AllowCharacter('\u2014');  // allow EM DASH through
+            services.AddWebEncoders((options) =>
             {
-                app.UseJson();
-            }
+                options.TextEncoderSettings = settings;
+            });
+        }
 
-            // Fortunes endpoints
-            if (Scenarios.DbFortunesRaw)
-            {
-                app.UseFortunesRaw();
-            }
+        if (Scenarios.Any("Mvc"))
+        {
+            var mvcBuilder = services.AddMvcCore();
 
-            if (Scenarios.DbFortunesDapper)
+            if (Scenarios.MvcViews || Scenarios.Any("MvcDbFortunes"))
             {
-                app.UseFortunesDapper();
+                mvcBuilder
+                    .AddViews()
+                    .AddRazorViewEngine();
             }
+        }
+    }
 
-            if (Scenarios.DbFortunesEf)
-            {
-                app.UseFortunesEf();
-            }
+    public void Configure(IApplicationBuilder app)
+    {
+        if (Scenarios.Plaintext)
+        {
+            app.UsePlainText();
+        }
 
-            // Single query endpoints
-            if (Scenarios.DbSingleQueryRaw)
-            {
-                app.UseSingleQueryRaw();
-            }
+        if (Scenarios.Json)
+        {
+            app.UseJson();
+        }
 
-            if (Scenarios.DbSingleQueryDapper)
-            {
-                app.UseSingleQueryDapper();
-            }
+        // Fortunes endpoints
+        if (Scenarios.DbFortunesRaw)
+        {
+            app.UseFortunesRaw();
+        }
 
-            if (Scenarios.DbSingleQueryEf)
-            {
-                app.UseSingleQueryEf();
-            }
+        if (Scenarios.DbFortunesDapper)
+        {
+            app.UseFortunesDapper();
+        }
 
-            // Multiple query endpoints
-            if (Scenarios.DbMultiQueryRaw)
-            {
-                app.UseMultipleQueriesRaw();
-            }
+        if (Scenarios.DbFortunesEf)
+        {
+            app.UseFortunesEf();
+        }
 
-            if (Scenarios.DbMultiQueryDapper)
-            {
-                app.UseMultipleQueriesDapper();
-            }
+        // Single query endpoints
+        if (Scenarios.DbSingleQueryRaw)
+        {
+            app.UseSingleQueryRaw();
+        }
 
-            if (Scenarios.DbMultiQueryEf)
-            {
-                app.UseMultipleQueriesEf();
-            }
+        if (Scenarios.DbSingleQueryDapper)
+        {
+            app.UseSingleQueryDapper();
+        }
 
-            // Multiple update endpoints
-            if (Scenarios.DbMultiUpdateRaw)
-            {
-                app.UseMultipleUpdatesRaw();
-            }
+        if (Scenarios.DbSingleQueryEf)
+        {
+            app.UseSingleQueryEf();
+        }
 
-            if (Scenarios.DbMultiUpdateDapper)
-            {
-                app.UseMultipleUpdatesDapper();
-            }
+        // Multiple query endpoints
+        if (Scenarios.DbMultiQueryRaw)
+        {
+            app.UseMultipleQueriesRaw();
+        }
 
-            if (Scenarios.DbMultiUpdateEf)
-            {
-                app.UseMultipleUpdatesEf();
-            }
+        if (Scenarios.DbMultiQueryDapper)
+        {
+            app.UseMultipleQueriesDapper();
+        }
 
-            if (Scenarios.Any("Mvc"))
-            {
-                app.UseRouting();
-            
-                app.UseEndpoints(endpoints =>
-                {
-                    endpoints.MapControllers();
-                });
-            }
+        if (Scenarios.DbMultiQueryEf)
+        {
+            app.UseMultipleQueriesEf();
+        }
+
+        // Multiple update endpoints
+        if (Scenarios.DbMultiUpdateRaw)
+        {
+            app.UseMultipleUpdatesRaw();
+        }
 
-            if (Scenarios.StaticFiles)
+        if (Scenarios.DbMultiUpdateDapper)
+        {
+            app.UseMultipleUpdatesDapper();
+        }
+
+        if (Scenarios.DbMultiUpdateEf)
+        {
+            app.UseMultipleUpdatesEf();
+        }
+
+        if (Scenarios.Any("Mvc"))
+        {
+            app.UseRouting();
+
+            app.UseEndpoints(endpoints =>
             {
-                app.UseStaticFiles();
-            }
+                endpoints.MapControllers();
+            });
+        }
+
+        if (Scenarios.StaticFiles)
+        {
+            app.UseStaticFiles();
         }
     }
 }

+ 36 - 38
frameworks/CSharp/aspnetcore/PlatformBenchmarks/AsciiString.cs

@@ -1,59 +1,57 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Text;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public readonly struct AsciiString : IEquatable<AsciiString>
 {
-    public readonly struct AsciiString : IEquatable<AsciiString>
-    {
-        private readonly byte[] _data;
+    private readonly byte[] _data;
 
-        public AsciiString(string s) => _data = Encoding.ASCII.GetBytes(s);
+    public AsciiString(string s) => _data = Encoding.ASCII.GetBytes(s);
 
-        private AsciiString(byte[] b) => _data = b;
+    private AsciiString(byte[] b) => _data = b;
 
-        public int Length => _data.Length;
+    public int Length => _data.Length;
 
-        public ReadOnlySpan<byte> AsSpan() => _data;
+    public ReadOnlySpan<byte> AsSpan() => _data;
 
-        public static implicit operator ReadOnlySpan<byte>(AsciiString str) => str._data;
-        public static implicit operator byte[] (AsciiString str) => str._data;
+    public static implicit operator ReadOnlySpan<byte>(AsciiString str) => str._data;
+    public static implicit operator byte[](AsciiString str) => str._data;
 
-        public static implicit operator AsciiString(string str) => new AsciiString(str);
+    public static implicit operator AsciiString(string str) => new(str);
 
-        public override string ToString() => Encoding.ASCII.GetString(_data);
-        public static explicit operator string(AsciiString str) => str.ToString();
+    public override string ToString() => Encoding.ASCII.GetString(_data);
+    public static explicit operator string(AsciiString str) => str.ToString();
 
-        public bool Equals(AsciiString other) => ReferenceEquals(_data, other._data) || SequenceEqual(_data, other._data);
-        private bool SequenceEqual(byte[] data1, byte[] data2) => new Span<byte>(data1).SequenceEqual(data2);
+    public bool Equals(AsciiString other) => ReferenceEquals(_data, other._data) || SequenceEqual(_data, other._data);
+    private bool SequenceEqual(byte[] data1, byte[] data2) => new Span<byte>(data1).SequenceEqual(data2);
 
-        public static bool operator ==(AsciiString a, AsciiString b) => a.Equals(b);
-        public static bool operator !=(AsciiString a, AsciiString b) => !a.Equals(b);
-        public override bool Equals(object other) => (other is AsciiString) && Equals((AsciiString)other);
+    public static bool operator ==(AsciiString a, AsciiString b) => a.Equals(b);
+    public static bool operator !=(AsciiString a, AsciiString b) => !a.Equals(b);
+    public override bool Equals(object other) => (other is AsciiString @string) && Equals(@string);
 
-        public static AsciiString operator +(AsciiString a, AsciiString b)
-        {
-            var result = new byte[a.Length + b.Length];
-            a._data.CopyTo(result, 0);
-            b._data.CopyTo(result, a.Length);
-            return new AsciiString(result);
-        }
+    public static AsciiString operator +(AsciiString a, AsciiString b)
+    {
+        var result = new byte[a.Length + b.Length];
+        a._data.CopyTo(result, 0);
+        b._data.CopyTo(result, a.Length);
+        return new AsciiString(result);
+    }
 
-        public override int GetHashCode()
+    public override int GetHashCode()
+    {
+        // Copied from x64 version of string.GetLegacyNonRandomizedHashCode()
+        // https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/String.Comparison.cs
+        var data = _data;
+        int hash1 = 5381;
+        int hash2 = hash1;
+        foreach (int b in data)
         {
-            // Copied from x64 version of string.GetLegacyNonRandomizedHashCode()
-            // https://github.com/dotnet/coreclr/blob/master/src/mscorlib/src/System/String.Comparison.cs
-            var data = _data;
-            int hash1 = 5381;
-            int hash2 = hash1;
-            foreach (int b in data)
-            {
-                hash1 = ((hash1 << 5) + hash1) ^ b;
-            }
-            return hash1 + (hash2 * 1566083941);
+            hash1 = ((hash1 << 5) + hash1) ^ b;
         }
-
+        return hash1 + (hash2 * 1566083941);
     }
+
 }

+ 5 - 6
frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.Caching.cs

@@ -6,14 +6,13 @@
 using System.IO.Pipelines;
 using System.Threading.Tasks;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication
 {
-    public partial class BenchmarkApplication
+    private async Task Caching(PipeWriter pipeWriter, int count)
     {
-        private async Task Caching(PipeWriter pipeWriter, int count)
-        {
-            OutputMultipleQueries(pipeWriter, await Db.LoadCachedQueries(count), SerializerContext.CachedWorldArray);
-        }
+        OutputMultipleQueries(pipeWriter, await Db.LoadCachedQueries(count), SerializerContext.CachedWorldArray);
     }
 }
 

+ 140 - 144
frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.HttpConnection.cs

@@ -1,141 +1,138 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Buffers;
 using System.IO.Pipelines;
 using System.Runtime.CompilerServices;
 using System.Text.Encodings.Web;
 using System.Text.Unicode;
-using System.Threading;
-using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication : IHttpConnection
 {
-    public partial class BenchmarkApplication : IHttpConnection
-    {
-        private State _state;
+    private State _state;
 
-        public PipeReader Reader { get; set; }
-        public PipeWriter Writer { get; set; }
+    public PipeReader Reader { get; set; }
+    public PipeWriter Writer { get; set; }
 
-        protected HtmlEncoder HtmlEncoder { get; } = CreateHtmlEncoder();
+    protected HtmlEncoder HtmlEncoder { get; } = CreateHtmlEncoder();
 
-        private HttpParser<ParsingAdapter> Parser { get; } = new HttpParser<ParsingAdapter>();
+    private HttpParser<ParsingAdapter> Parser { get; } = new HttpParser<ParsingAdapter>();
 
-        public async Task ExecuteAsync()
+    public async Task ExecuteAsync()
+    {
+        try
         {
-            try
-            {
-                await ProcessRequestsAsync();
+            await ProcessRequestsAsync();
 
-                Reader.Complete();
-            }
-            catch (Exception ex)
-            {
-                Reader.Complete(ex);
-            }
-            finally
-            {
-                Writer.Complete();
-            }
+            Reader.Complete();
         }
-
-        private static HtmlEncoder CreateHtmlEncoder()
+        catch (Exception ex)
+        {
+            Reader.Complete(ex);
+        }
+        finally
         {
-            var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
-            settings.AllowCharacter('\u2014');  // allow EM DASH through
-            return HtmlEncoder.Create(settings);
+            Writer.Complete();
         }
+    }
+
+    private static HtmlEncoder CreateHtmlEncoder()
+    {
+        var settings = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Katakana, UnicodeRanges.Hiragana);
+        settings.AllowCharacter('\u2014');  // allow EM DASH through
+        return HtmlEncoder.Create(settings);
+    }
 
 #if !DATABASE
-        private async Task ProcessRequestsAsync()
+    private async Task ProcessRequestsAsync()
+    {
+        while (true)
         {
-            while (true)
-            {
-                var readResult = await Reader.ReadAsync(default);
-                var buffer = readResult.Buffer;
-                var isCompleted = readResult.IsCompleted;
+            var readResult = await Reader.ReadAsync(default);
+            var buffer = readResult.Buffer;
+            var isCompleted = readResult.IsCompleted;
 
-                if (buffer.IsEmpty && isCompleted)
-                {
-                    return;
-                }
-
-                if (!HandleRequests(buffer, isCompleted))
-                {
-                    return;
-                }
+            if (buffer.IsEmpty && isCompleted)
+            {
+                return;
+            }
 
-                await Writer.FlushAsync(default);
+            if (!HandleRequests(buffer, isCompleted))
+            {
+                return;
             }
+
+            await Writer.FlushAsync(default);
         }
+    }
 
-        private bool HandleRequests(in ReadOnlySequence<byte> buffer, bool isCompleted)
-        {
-            var reader = new SequenceReader<byte>(buffer);
-            var writer = GetWriter(Writer, sizeHint: 160 * 16); // 160*16 is for Plaintext, for Json 160 would be enough
+    private bool HandleRequests(in ReadOnlySequence<byte> buffer, bool isCompleted)
+    {
+        var reader = new SequenceReader<byte>(buffer);
+        var writer = GetWriter(Writer, sizeHint: 160 * 16); // 160*16 is for Plaintext, for Json 160 would be enough
 
-            while (true)
+        while (true)
+        {
+            if (!ParseHttpRequest(ref reader, isCompleted))
             {
-                if (!ParseHttpRequest(ref reader, isCompleted))
-                {
-                    return false;
-                }
+                return false;
+            }
 
-                if (_state == State.Body)
-                {
-                    ProcessRequest(ref writer);
+            if (_state == State.Body)
+            {
+                ProcessRequest(ref writer);
 
-                    _state = State.StartLine;
+                _state = State.StartLine;
 
-                    if (!reader.End)
-                    {
-                        // More input data to parse
-                        continue;
-                    }
+                if (!reader.End)
+                {
+                    // More input data to parse
+                    continue;
                 }
-
-                // No more input or incomplete data, Advance the Reader
-                Reader.AdvanceTo(reader.Position, buffer.End);
-                break;
             }
 
-            writer.Commit();
-            return true;
+            // No more input or incomplete data, Advance the Reader
+            Reader.AdvanceTo(reader.Position, buffer.End);
+            break;
         }
 
-        private bool ParseHttpRequest(ref SequenceReader<byte> reader, bool isCompleted)
-        {
-            var state = _state;
+        writer.Commit();
+        return true;
+    }
 
-            if (state == State.StartLine)
-            {
-                if (Parser.ParseRequestLine(new ParsingAdapter(this), ref reader))
-                {
-                    state = State.Headers;
-                }
-            }
+    private bool ParseHttpRequest(ref SequenceReader<byte> reader, bool isCompleted)
+    {
+        var state = _state;
 
-            if (state == State.Headers)
+        if (state == State.StartLine)
+        {
+            if (Parser.ParseRequestLine(new ParsingAdapter(this), ref reader))
             {
-                var success = Parser.ParseHeaders(new ParsingAdapter(this), ref reader);
-
-                if (success)
-                {
-                    state = State.Body;
-                }
+                state = State.Headers;
             }
+        }
 
-            if (state != State.Body && isCompleted)
+        if (state == State.Headers)
+        {
+            var success = Parser.ParseHeaders(new ParsingAdapter(this), ref reader);
+
+            if (success)
             {
-                ThrowUnexpectedEndOfData();
+                state = State.Body;
             }
+        }
 
-            _state = state;
-            return true;
+        if (state != State.Body && isCompleted)
+        {
+            ThrowUnexpectedEndOfData();
         }
+
+        _state = state;
+        return true;
+    }
 #else
         private async Task ProcessRequestsAsync()
         {
@@ -224,76 +221,75 @@ namespace PlatformBenchmarks
         }
 #endif
 
-        public void OnStaticIndexedHeader(int index)
-        {
-        }
+    public void OnStaticIndexedHeader(int index)
+    {
+    }
 
-        public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
-        {
-        }
+    public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
+    {
+    }
 
-        public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
-        {
-        }
+    public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
+    {
+    }
 
-        public void OnHeadersComplete(bool endStream)
-        {
-        }
+    public void OnHeadersComplete(bool endStream)
+    {
+    }
 
-        private static void ThrowUnexpectedEndOfData()
-        {
-            throw new InvalidOperationException("Unexpected end of data!");
-        }
+    private static void ThrowUnexpectedEndOfData()
+    {
+        throw new InvalidOperationException("Unexpected end of data!");
+    }
 
-        private enum State
-        {
-            StartLine,
-            Headers,
-            Body
-        }
+    private enum State
+    {
+        StartLine,
+        Headers,
+        Body
+    }
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        private static BufferWriter<WriterAdapter> GetWriter(PipeWriter pipeWriter, int sizeHint)
-            => new BufferWriter<WriterAdapter>(new WriterAdapter(pipeWriter), sizeHint);
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    private static BufferWriter<WriterAdapter> GetWriter(PipeWriter pipeWriter, int sizeHint)
+        => new(new WriterAdapter(pipeWriter), sizeHint);
 
-        private struct WriterAdapter : IBufferWriter<byte>
-        {
-            public PipeWriter Writer;
+    private struct WriterAdapter : IBufferWriter<byte>
+    {
+        public PipeWriter Writer;
 
-            public WriterAdapter(PipeWriter writer)
-                => Writer = writer;
+        public WriterAdapter(PipeWriter writer)
+            => Writer = writer;
 
-            public void Advance(int count)
-                => Writer.Advance(count);
+        public void Advance(int count)
+            => Writer.Advance(count);
 
-            public Memory<byte> GetMemory(int sizeHint = 0)
-                => Writer.GetMemory(sizeHint);
+        public Memory<byte> GetMemory(int sizeHint = 0)
+            => Writer.GetMemory(sizeHint);
 
-            public Span<byte> GetSpan(int sizeHint = 0)
-                => Writer.GetSpan(sizeHint);
-        }
+        public Span<byte> GetSpan(int sizeHint = 0)
+            => Writer.GetSpan(sizeHint);
+    }
 
-        private struct ParsingAdapter : IHttpRequestLineHandler, IHttpHeadersHandler
-        {
-            public BenchmarkApplication RequestHandler;
+    private struct ParsingAdapter : IHttpRequestLineHandler, IHttpHeadersHandler
+    {
+        public BenchmarkApplication RequestHandler;
 
-            public ParsingAdapter(BenchmarkApplication requestHandler)
-                => RequestHandler = requestHandler;
+        public ParsingAdapter(BenchmarkApplication requestHandler)
+            => RequestHandler = requestHandler;
 
-            public void OnStaticIndexedHeader(int index) 
-                => RequestHandler.OnStaticIndexedHeader(index);
+        public void OnStaticIndexedHeader(int index)
+            => RequestHandler.OnStaticIndexedHeader(index);
 
-            public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
-                => RequestHandler.OnStaticIndexedHeader(index, value);
+        public void OnStaticIndexedHeader(int index, ReadOnlySpan<byte> value)
+            => RequestHandler.OnStaticIndexedHeader(index, value);
 
-            public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
-                => RequestHandler.OnHeader(name, value);
+        public void OnHeader(ReadOnlySpan<byte> name, ReadOnlySpan<byte> value)
+            => RequestHandler.OnHeader(name, value);
 
-            public void OnHeadersComplete(bool endStream)
-                => RequestHandler.OnHeadersComplete(endStream);
+        public void OnHeadersComplete(bool endStream)
+            => RequestHandler.OnHeadersComplete(endStream);
 
-            public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
-                => RequestHandler.OnStartLine(versionAndMethod, targetPath, startLine);
-        }
+        public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
+            => RequestHandler.OnStartLine(versionAndMethod, targetPath, startLine);
     }
 }

+ 19 - 20
frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.Json.cs

@@ -4,32 +4,31 @@
 using System.Buffers;
 using System.Text.Json;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication
 {
-    public partial class BenchmarkApplication
-    {
-        private readonly static uint _jsonPayloadSize = (uint)JsonSerializer.SerializeToUtf8Bytes(new JsonMessage { message = "Hello, World!" }, SerializerContext.JsonMessage).Length;
+    private readonly static uint _jsonPayloadSize = (uint)JsonSerializer.SerializeToUtf8Bytes(new JsonMessage { message = "Hello, World!" }, SerializerContext.JsonMessage).Length;
 
-        private readonly static AsciiString _jsonPreamble =
-            _http11OK +
-            _headerServer + _crlf +
-            _headerContentTypeJson + _crlf +
-            _headerContentLength + _jsonPayloadSize.ToString();
+    private readonly static AsciiString _jsonPreamble =
+        _http11OK +
+        _headerServer + _crlf +
+        _headerContentTypeJson + _crlf +
+        _headerContentLength + _jsonPayloadSize.ToString();
 
-        private static void Json(ref BufferWriter<WriterAdapter> writer, IBufferWriter<byte> bodyWriter)
-        {
-            writer.Write(_jsonPreamble);
+    private static void Json(ref BufferWriter<WriterAdapter> writer, IBufferWriter<byte> bodyWriter)
+    {
+        writer.Write(_jsonPreamble);
 
-            // Date header
-            writer.Write(DateHeader.HeaderBytes);
+        // Date header
+        writer.Write(DateHeader.HeaderBytes);
 
-            writer.Commit();
+        writer.Commit();
 
-            Utf8JsonWriter utf8JsonWriter = t_writer ??= new Utf8JsonWriter(bodyWriter, new JsonWriterOptions { SkipValidation = true });
-            utf8JsonWriter.Reset(bodyWriter);
+        Utf8JsonWriter utf8JsonWriter = t_writer ??= new Utf8JsonWriter(bodyWriter, new JsonWriterOptions { SkipValidation = true });
+        utf8JsonWriter.Reset(bodyWriter);
 
-            // Body
-            JsonSerializer.Serialize(utf8JsonWriter, new JsonMessage { message = "Hello, World!" }, SerializerContext.JsonMessage);        
-        }
+        // Body
+        JsonSerializer.Serialize(utf8JsonWriter, new JsonMessage { message = "Hello, World!" }, SerializerContext.JsonMessage);
     }
 }

+ 15 - 16
frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.Plaintext.cs

@@ -1,25 +1,24 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication
 {
-    public partial class BenchmarkApplication
-    {
-        private readonly static AsciiString _plaintextPreamble =
-            _http11OK +
-            _headerServer + _crlf +
-            _headerContentTypeText + _crlf +
-            _headerContentLength + _plainTextBody.Length.ToString();
+    private readonly static AsciiString _plaintextPreamble =
+        _http11OK +
+        _headerServer + _crlf +
+        _headerContentTypeText + _crlf +
+        _headerContentLength + _plainTextBody.Length.ToString();
 
-        private static void PlainText(ref BufferWriter<WriterAdapter> writer)
-        {
-            writer.Write(_plaintextPreamble);
+    private static void PlainText(ref BufferWriter<WriterAdapter> writer)
+    {
+        writer.Write(_plaintextPreamble);
 
-            // Date header
-            writer.Write(DateHeader.HeaderBytes);
+        // Date header
+        writer.Write(DateHeader.HeaderBytes);
 
-            // Body
-            writer.Write(_plainTextBody);
-        }
+        // Body
+        writer.Write(_plainTextBody);
     }
 }

+ 103 - 104
frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkApplication.cs

@@ -10,86 +10,86 @@ using System.Threading.Tasks;
 
 using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public partial class BenchmarkApplication
 {
-    public partial class BenchmarkApplication
+    private readonly static AsciiString _applicationName = "Kestrel Platform-Level Application";
+    public static AsciiString ApplicationName => _applicationName;
+
+    private readonly static AsciiString _crlf = "\r\n";
+    private readonly static AsciiString _eoh = "\r\n\r\n"; // End Of Headers
+    private readonly static AsciiString _http11OK = "HTTP/1.1 200 OK\r\n";
+    private readonly static AsciiString _http11NotFound = "HTTP/1.1 404 Not Found\r\n";
+    private readonly static AsciiString _headerServer = "Server: K";
+    private readonly static AsciiString _headerContentLength = "Content-Length: ";
+    private readonly static AsciiString _headerContentLengthZero = "Content-Length: 0";
+    private readonly static AsciiString _headerContentTypeText = "Content-Type: text/plain";
+    private readonly static AsciiString _headerContentTypeJson = "Content-Type: application/json";
+    private readonly static AsciiString _headerContentTypeHtml = "Content-Type: text/html; charset=UTF-8";
+
+    private readonly static AsciiString _dbPreamble =
+        _http11OK +
+        _headerServer + _crlf +
+        _headerContentTypeJson + _crlf +
+        _headerContentLength;
+
+    private readonly static AsciiString _plainTextBody = "Hello, World!";
+
+    private static readonly JsonContext SerializerContext = JsonContext.Default;
+
+    [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Serialization, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
+    [JsonSerializable(typeof(JsonMessage))]
+    [JsonSerializable(typeof(CachedWorld[]))]
+    [JsonSerializable(typeof(World[]))]
+    private sealed partial class JsonContext : JsonSerializerContext
     {
-        private readonly static AsciiString _applicationName = "Kestrel Platform-Level Application";
-        public static AsciiString ApplicationName => _applicationName;
-
-        private readonly static AsciiString _crlf = "\r\n";
-        private readonly static AsciiString _eoh = "\r\n\r\n"; // End Of Headers
-        private readonly static AsciiString _http11OK = "HTTP/1.1 200 OK\r\n";
-        private readonly static AsciiString _http11NotFound = "HTTP/1.1 404 Not Found\r\n";
-        private readonly static AsciiString _headerServer = "Server: K";
-        private readonly static AsciiString _headerContentLength = "Content-Length: ";
-        private readonly static AsciiString _headerContentLengthZero = "Content-Length: 0";
-        private readonly static AsciiString _headerContentTypeText = "Content-Type: text/plain";
-        private readonly static AsciiString _headerContentTypeJson = "Content-Type: application/json";
-        private readonly static AsciiString _headerContentTypeHtml = "Content-Type: text/html; charset=UTF-8";
-
-        private readonly static AsciiString _dbPreamble =
-            _http11OK +
-            _headerServer + _crlf +
-            _headerContentTypeJson + _crlf +
-            _headerContentLength;
-
-        private readonly static AsciiString _plainTextBody = "Hello, World!";
-
-        private static readonly JsonContext SerializerContext = JsonContext.Default;
-
-        [JsonSourceGenerationOptions(GenerationMode = JsonSourceGenerationMode.Serialization, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
-        [JsonSerializable(typeof(JsonMessage))]
-        [JsonSerializable(typeof(CachedWorld[]))]
-        [JsonSerializable(typeof(World[]))]
-        private sealed partial class JsonContext : JsonSerializerContext
-        {
-        }
+    }
 
-        private readonly static AsciiString _fortunesTableStart = "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>";
-        private readonly static AsciiString _fortunesRowStart = "<tr><td>";
-        private readonly static AsciiString _fortunesColumn = "</td><td>";
-        private readonly static AsciiString _fortunesRowEnd = "</td></tr>";
-        private readonly static AsciiString _fortunesTableEnd = "</table></body></html>";
-        private readonly static AsciiString _contentLengthGap = new string(' ', 4);
+    private readonly static AsciiString _fortunesTableStart = "<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>";
+    private readonly static AsciiString _fortunesRowStart = "<tr><td>";
+    private readonly static AsciiString _fortunesColumn = "</td><td>";
+    private readonly static AsciiString _fortunesRowEnd = "</td></tr>";
+    private readonly static AsciiString _fortunesTableEnd = "</table></body></html>";
+    private readonly static AsciiString _contentLengthGap = new string(' ', 4);
 
 #if DATABASE
         public static RawDb Db { get; set; }
 #endif
 
-        [ThreadStatic]
-        private static Utf8JsonWriter t_writer;
+    [ThreadStatic]
+    private static Utf8JsonWriter t_writer;
 
-        public static class Paths
-        {
-            public readonly static AsciiString Json = "/json";
-            public readonly static AsciiString Plaintext = "/plaintext";
-            public readonly static AsciiString SingleQuery = "/db";
-            public readonly static AsciiString Fortunes = "/fortunes";
-            public readonly static AsciiString Updates = "/updates/";
-            public readonly static AsciiString MultipleQueries = "/queries/";
-            public readonly static AsciiString Caching = "/cached-worlds/";
-        }
+    public static class Paths
+    {
+        public readonly static AsciiString Json = "/json";
+        public readonly static AsciiString Plaintext = "/plaintext";
+        public readonly static AsciiString SingleQuery = "/db";
+        public readonly static AsciiString Fortunes = "/fortunes";
+        public readonly static AsciiString Updates = "/updates/";
+        public readonly static AsciiString MultipleQueries = "/queries/";
+        public readonly static AsciiString Caching = "/cached-worlds/";
+    }
+
+    private RequestType _requestType;
+    private int _queries;
 
-        private RequestType _requestType;
-        private int _queries;
+    public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
+    {
+        _requestType = versionAndMethod.Method == Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpMethod.Get ? GetRequestType(startLine.Slice(targetPath.Offset, targetPath.Length), ref _queries) : RequestType.NotRecognized;
+    }
 
-        public void OnStartLine(HttpVersionAndMethod versionAndMethod, TargetOffsetPathLength targetPath, Span<byte> startLine)
+    private RequestType GetRequestType(ReadOnlySpan<byte> path, ref int queries)
+    {
+#if !DATABASE
+        if (path.Length == 10 && path.SequenceEqual(Paths.Plaintext))
         {
-            _requestType = versionAndMethod.Method == HttpMethod.Get ? GetRequestType(startLine.Slice(targetPath.Offset, targetPath.Length), ref _queries) : RequestType.NotRecognized;
+            return RequestType.PlainText;
         }
-
-        private RequestType GetRequestType(ReadOnlySpan<byte> path, ref int queries)
+        else if (path.Length == 5 && path.SequenceEqual(Paths.Json))
         {
-#if !DATABASE
-            if (path.Length == 10 && path.SequenceEqual(Paths.Plaintext))
-            {
-                return RequestType.PlainText;
-            }
-            else if (path.Length == 5 && path.SequenceEqual(Paths.Json))
-            {
-                return RequestType.Json;
-            }
+            return RequestType.Json;
+        }
 #else
             if (path.Length == 3 && path[0] == '/' && path[1] == 'd' && path[2] == 'b')
             {
@@ -115,26 +115,26 @@ namespace PlatformBenchmarks
                 return RequestType.MultipleQueries;
             }
 #endif
-            return RequestType.NotRecognized;
-        }
+        return RequestType.NotRecognized;
+    }
 
 
 #if !DATABASE
-        private void ProcessRequest(ref BufferWriter<WriterAdapter> writer)
+    private void ProcessRequest(ref BufferWriter<WriterAdapter> writer)
+    {
+        if (_requestType == RequestType.PlainText)
         {
-            if (_requestType == RequestType.PlainText)
-            {
-                PlainText(ref writer);
-            }
-            else if (_requestType == RequestType.Json)
-            {
-                Json(ref writer, Writer);
-            }
-            else
-            {
-                Default(ref writer);
-            }
+            PlainText(ref writer);
         }
+        else if (_requestType == RequestType.Json)
+        {
+            Json(ref writer, Writer);
+        }
+        else
+        {
+            Default(ref writer);
+        }
+    }
 #else
 
         private static int ParseQueries(ReadOnlySpan<byte> parameter)
@@ -169,30 +169,29 @@ namespace PlatformBenchmarks
             return Task.CompletedTask;
         }
 #endif
-        private readonly static AsciiString _defaultPreamble =
-            _http11NotFound +
-            _headerServer + _crlf +
-            _headerContentTypeText + _crlf +
-            _headerContentLengthZero;
+    private readonly static AsciiString _defaultPreamble =
+        _http11NotFound +
+        _headerServer + _crlf +
+        _headerContentTypeText + _crlf +
+        _headerContentLengthZero;
 
-        private static void Default(ref BufferWriter<WriterAdapter> writer)
-        {
-            writer.Write(_defaultPreamble);
+    private static void Default(ref BufferWriter<WriterAdapter> writer)
+    {
+        writer.Write(_defaultPreamble);
 
-            // Date header
-            writer.Write(DateHeader.HeaderBytes);
-        }
+        // Date header
+        writer.Write(DateHeader.HeaderBytes);
+    }
 
-        private enum RequestType
-        {
-            NotRecognized,
-            PlainText,
-            Json,
-            Fortunes,
-            SingleQuery,
-            Caching,
-            Updates,
-            MultipleQueries
-        }
+    private enum RequestType
+    {
+        NotRecognized,
+        PlainText,
+        Json,
+        Fortunes,
+        SingleQuery,
+        Caching,
+        Updates,
+        MultipleQueries
     }
-}
+}

+ 36 - 42
frameworks/CSharp/aspnetcore/PlatformBenchmarks/BenchmarkConfigurationHelpers.cs

@@ -1,64 +1,58 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Net;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.AspNetCore.Http;
-using Microsoft.Extensions.Configuration;
-using System.IO.Pipelines;
 using System.Runtime.InteropServices;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public static class BenchmarkConfigurationHelpers
 {
-    public static class BenchmarkConfigurationHelpers
+    public static IWebHostBuilder UseBenchmarksConfiguration(this IWebHostBuilder builder, IConfiguration configuration)
     {
-        public static IWebHostBuilder UseBenchmarksConfiguration(this IWebHostBuilder builder, IConfiguration configuration)
+        builder.UseConfiguration(configuration);
+
+        builder.UseSockets(options =>
         {
-            builder.UseConfiguration(configuration);
+            if (int.TryParse(builder.GetSetting("threadCount"), out int threadCount))
+            {
+                options.IOQueueCount = threadCount;
+            }
 
-            builder.UseSockets(options =>
+            options.WaitForDataBeforeAllocatingBuffer = false;
+            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
             {
-                if (int.TryParse(builder.GetSetting("threadCount"), out int threadCount))
-                {
-                    options.IOQueueCount = threadCount;
-                }
+                options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
+            }
 
-                options.WaitForDataBeforeAllocatingBuffer = false;
-                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
-                {
-                    options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
-                }
+            Console.WriteLine($"Options: WaitForData={options.WaitForDataBeforeAllocatingBuffer}, PreferInlineScheduling={options.UnsafePreferInlineScheduling}, IOQueue={options.IOQueueCount}");
+        });
 
-                Console.WriteLine($"Options: WaitForData={options.WaitForDataBeforeAllocatingBuffer}, PreferInlineScheduling={options.UnsafePreferInlineScheduling}, IOQueue={options.IOQueueCount}");
-            });
+        return builder;
+    }
 
-            return builder;
-        }
+    public static IPEndPoint CreateIPEndPoint(this IConfiguration config)
+    {
+        var url = config["server.urls"] ?? config["urls"];
 
-        public static IPEndPoint CreateIPEndPoint(this IConfiguration config)
+        if (string.IsNullOrEmpty(url))
         {
-            var url = config["server.urls"] ?? config["urls"];
-
-            if (string.IsNullOrEmpty(url))
-            {
-                return new IPEndPoint(IPAddress.Loopback, 8080);
-            }
-
-            var address = BindingAddress.Parse(url);
+            return new IPEndPoint(IPAddress.Loopback, 8080);
+        }
 
-            IPAddress ip;
+        var address = BindingAddress.Parse(url);
 
-            if (string.Equals(address.Host, "localhost", StringComparison.OrdinalIgnoreCase))
-            {
-                ip = IPAddress.Loopback;
-            }
-            else if (!IPAddress.TryParse(address.Host, out ip))
-            {
-                ip = IPAddress.IPv6Any;
-            }
+        IPAddress ip;
 
-            return new IPEndPoint(ip, address.Port);
+        if (string.Equals(address.Host, "localhost", StringComparison.OrdinalIgnoreCase))
+        {
+            ip = IPAddress.Loopback;
         }
+        else if (!IPAddress.TryParse(address.Host, out ip))
+        {
+            ip = IPAddress.IPv6Any;
+        }
+
+        return new IPEndPoint(ip, address.Port);
     }
 }

+ 44 - 45
frameworks/CSharp/aspnetcore/PlatformBenchmarks/BufferExtensions.cs

@@ -6,58 +6,57 @@ using System.Buffers;
 using System.Runtime.CompilerServices;
 using System.Text;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+// Same as KestrelHttpServer\src\Kestrel.Core\Internal\Http\PipelineExtensions.cs
+// However methods accept T : struct, IBufferWriter<byte> rather than PipeWriter.
+// This allows a struct wrapper to turn CountingBufferWriter into a non-shared generic,
+// while still offering the WriteNumeric extension.
+
+public static class BufferExtensions
 {
-    // Same as KestrelHttpServer\src\Kestrel.Core\Internal\Http\PipelineExtensions.cs
-    // However methods accept T : struct, IBufferWriter<byte> rather than PipeWriter.
-    // This allows a struct wrapper to turn CountingBufferWriter into a non-shared generic,
-    // while still offering the WriteNumeric extension.
+    private const int _maxULongByteLength = 20;
 
-    public static class BufferExtensions
-    {
-        private const int _maxULongByteLength = 20;
+    [ThreadStatic]
+    private static byte[] _numericBytesScratch;
 
-        [ThreadStatic]
-        private static byte[] _numericBytesScratch;
+    internal static void WriteUtf8String<T>(ref this BufferWriter<T> buffer, string text)
+         where T : struct, IBufferWriter<byte>
+    {
+        var byteCount = Encoding.UTF8.GetByteCount(text);
+        buffer.Ensure(byteCount);
+        byteCount = Encoding.UTF8.GetBytes(text.AsSpan(), buffer.Span);
+        buffer.Advance(byteCount);
+    }
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    internal static void WriteNumericMultiWrite<T>(ref this BufferWriter<T> buffer, uint number)
+         where T : IBufferWriter<byte>
+    {
+        const byte AsciiDigitStart = (byte)'0';
 
-        internal static void WriteUtf8String<T>(ref this BufferWriter<T> buffer, string text)
-             where T : struct, IBufferWriter<byte>
+        var value = number;
+        var position = _maxULongByteLength;
+        var byteBuffer = NumericBytesScratch;
+        do
         {
-            var byteCount = Encoding.UTF8.GetByteCount(text);
-            buffer.Ensure(byteCount);
-            byteCount = Encoding.UTF8.GetBytes(text.AsSpan(), buffer.Span);
-            buffer.Advance(byteCount);
-        }
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        internal static void WriteNumericMultiWrite<T>(ref this BufferWriter<T> buffer, uint number)
-             where T : IBufferWriter<byte>
-        {
-            const byte AsciiDigitStart = (byte)'0';
-
-            var value = number;
-            var position = _maxULongByteLength;
-            var byteBuffer = NumericBytesScratch;
-            do
-            {
-                // Consider using Math.DivRem() if available
-                var quotient = value / 10;
-                byteBuffer[--position] = (byte)(AsciiDigitStart + (value - quotient * 10)); // 0x30 = '0'
-                value = quotient;
-            }
-            while (value != 0);
-
-            var length = _maxULongByteLength - position;
-            buffer.Write(new ReadOnlySpan<byte>(byteBuffer, position, length));
+            // Consider using Math.DivRem() if available
+            var quotient = value / 10;
+            byteBuffer[--position] = (byte)(AsciiDigitStart + (value - quotient * 10)); // 0x30 = '0'
+            value = quotient;
         }
+        while (value != 0);
 
-        private static byte[] NumericBytesScratch => _numericBytesScratch ?? CreateNumericBytesScratch();
+        var length = _maxULongByteLength - position;
+        buffer.Write(new ReadOnlySpan<byte>(byteBuffer, position, length));
+    }
 
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static byte[] CreateNumericBytesScratch()
-        {
-            var bytes = new byte[_maxULongByteLength];
-            _numericBytesScratch = bytes;
-            return bytes;
-        }
+    private static byte[] NumericBytesScratch => _numericBytesScratch ?? CreateNumericBytesScratch();
+
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    private static byte[] CreateNumericBytesScratch()
+    {
+        var bytes = new byte[_maxULongByteLength];
+        _numericBytesScratch = bytes;
+        return bytes;
     }
 }

+ 99 - 101
frameworks/CSharp/aspnetcore/PlatformBenchmarks/BufferWriter.cs

@@ -1,143 +1,141 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Buffers;
 using System.Runtime.CompilerServices;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public ref struct BufferWriter<T> where T : IBufferWriter<byte>
 {
-    public ref struct BufferWriter<T> where T : IBufferWriter<byte>
-    {
-        private T _output;
-        private Span<byte> _span;
-        private int _buffered;
+    private readonly T _output;
+    private Span<byte> _span;
+    private int _buffered;
 
-        public BufferWriter(T output, int sizeHint)
-        {
-            _buffered = 0;
-            _output = output;
-            _span = output.GetSpan(sizeHint);
-        }
+    public BufferWriter(T output, int sizeHint)
+    {
+        _buffered = 0;
+        _output = output;
+        _span = output.GetSpan(sizeHint);
+    }
 
-        public Span<byte> Span => _span;
+    public Span<byte> Span => _span;
 
-        public T Output => _output;
+    public T Output => _output;
 
-        public int Buffered => _buffered;
+    public int Buffered => _buffered;
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Commit()
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Commit()
+    {
+        var buffered = _buffered;
+        if (buffered > 0)
         {
-            var buffered = _buffered;
-            if (buffered > 0)
-            {
-                _buffered = 0;
-                _output.Advance(buffered);
-            }
+            _buffered = 0;
+            _output.Advance(buffered);
         }
+    }
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Advance(int count)
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Advance(int count)
+    {
+        _buffered += count;
+        _span = _span.Slice(count);
+    }
+
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Write(ReadOnlySpan<byte> source)
+    {
+        if (_span.Length >= source.Length)
         {
-            _buffered += count;
-            _span = _span.Slice(count);
+            source.CopyTo(_span);
+            Advance(source.Length);
         }
-
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Write(ReadOnlySpan<byte> source)
+        else
         {
-            if (_span.Length >= source.Length)
-            {
-                source.CopyTo(_span);
-                Advance(source.Length);
-            }
-            else
-            {
-                WriteMultiBuffer(source);
-            }
+            WriteMultiBuffer(source);
         }
+    }
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        public void Ensure(int count = 1)
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    public void Ensure(int count = 1)
+    {
+        if (_span.Length < count)
         {
-            if (_span.Length < count)
-            {
-                EnsureMore(count);
-            }
+            EnsureMore(count);
         }
+    }
 
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private void EnsureMore(int count = 0)
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    private void EnsureMore(int count = 0)
+    {
+        if (_buffered > 0)
         {
-            if (_buffered > 0)
-            {
-                Commit();
-            }
-
-            _span = _output.GetSpan(count);
+            Commit();
         }
 
-        private void WriteMultiBuffer(ReadOnlySpan<byte> source)
+        _span = _output.GetSpan(count);
+    }
+
+    private void WriteMultiBuffer(ReadOnlySpan<byte> source)
+    {
+        while (source.Length > 0)
         {
-            while (source.Length > 0)
+            if (_span.Length == 0)
             {
-                if (_span.Length == 0)
-                {
-                    EnsureMore();
-                }
-
-                var writable = Math.Min(source.Length, _span.Length);
-                source.Slice(0, writable).CopyTo(_span);
-                source = source.Slice(writable);
-                Advance(writable);
+                EnsureMore();
             }
+
+            var writable = Math.Min(source.Length, _span.Length);
+            source[..writable].CopyTo(_span);
+            source = source[writable..];
+            Advance(writable);
         }
+    }
 
-        [MethodImpl(MethodImplOptions.AggressiveInlining)]
-        internal void WriteNumeric(uint number)
-        {
-            const byte AsciiDigitStart = (byte)'0';
+    [MethodImpl(MethodImplOptions.AggressiveInlining)]
+    internal void WriteNumeric(uint number)
+    {
+        const byte AsciiDigitStart = (byte)'0';
 
-            var span = this.Span;
+        var span = this.Span;
 
-            // Fast path, try copying to the available memory directly
-            var advanceBy = 0;
-            if (span.Length >= 3)
+        // Fast path, try copying to the available memory directly
+        var advanceBy = 0;
+        if (span.Length >= 3)
+        {
+            if (number < 10)
             {
-                if (number < 10)
-                {
-                    span[0] = (byte)(number + AsciiDigitStart);
-                    advanceBy = 1;
-                }
-                else if (number < 100)
-                {
-                    var tens = (byte)((number * 205u) >> 11); // div10, valid to 1028
-
-                    span[0] = (byte)(tens + AsciiDigitStart);
-                    span[1] = (byte)(number - (tens * 10) + AsciiDigitStart);
-                    advanceBy = 2;
-                }
-                else if (number < 1000)
-                {
-                    var digit0 = (byte)((number * 41u) >> 12); // div100, valid to 1098
-                    var digits01 = (byte)((number * 205u) >> 11); // div10, valid to 1028
-
-                    span[0] = (byte)(digit0 + AsciiDigitStart);
-                    span[1] = (byte)(digits01 - (digit0 * 10) + AsciiDigitStart);
-                    span[2] = (byte)(number - (digits01 * 10) + AsciiDigitStart);
-                    advanceBy = 3;
-                }
+                span[0] = (byte)(number + AsciiDigitStart);
+                advanceBy = 1;
             }
-
-            if (advanceBy > 0)
+            else if (number < 100)
             {
-                Advance(advanceBy);
+                var tens = (byte)((number * 205u) >> 11); // div10, valid to 1028
+
+                span[0] = (byte)(tens + AsciiDigitStart);
+                span[1] = (byte)(number - (tens * 10) + AsciiDigitStart);
+                advanceBy = 2;
             }
-            else
+            else if (number < 1000)
             {
-                BufferExtensions.WriteNumericMultiWrite(ref this, number);
+                var digit0 = (byte)((number * 41u) >> 12); // div100, valid to 1098
+                var digits01 = (byte)((number * 205u) >> 11); // div10, valid to 1028
+
+                span[0] = (byte)(digit0 + AsciiDigitStart);
+                span[1] = (byte)(digits01 - (digit0 * 10) + AsciiDigitStart);
+                span[2] = (byte)(number - (digits01 * 10) + AsciiDigitStart);
+                advanceBy = 3;
             }
         }
+
+        if (advanceBy > 0)
+        {
+            Advance(advanceBy);
+        }
+        else
+        {
+            BufferExtensions.WriteNumericMultiWrite(ref this, number);
+        }
     }
 }

+ 5 - 6
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Configuration/AppSettings.cs

@@ -1,12 +1,11 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public class AppSettings
 {
-    public class AppSettings
-    {
-        public string ConnectionString { get; set; }
+    public string ConnectionString { get; set; }
 
-        public DatabaseServer Database { get; set; } = DatabaseServer.None;
-    }
+    public DatabaseServer Database { get; set; } = DatabaseServer.None;
 }

+ 7 - 8
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Configuration/DatabaseServer.cs

@@ -1,13 +1,12 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public enum DatabaseServer
 {
-    public enum DatabaseServer
-    {
-        None,
-        SqlServer,
-        PostgreSql,
-        MySql
-    }
+    None,
+    SqlServer,
+    PostgreSql,
+    MySql
 }

+ 28 - 31
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/BatchUpdateString.cs

@@ -1,44 +1,41 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System.Linq;
+namespace PlatformBenchmarks;
 
-namespace PlatformBenchmarks
+internal class BatchUpdateString
 {
-    internal class BatchUpdateString
-    {
-        private const int MaxBatch = 500;
+    private const int MaxBatch = 500;
+
+    public static DatabaseServer DatabaseServer;
+
+    internal static readonly string[] Ids = Enumerable.Range(0, MaxBatch).Select(i => $"@Id_{i}").ToArray();
+    internal static readonly string[] Randoms = Enumerable.Range(0, MaxBatch).Select(i => $"@Random_{i}").ToArray();
 
-        public static DatabaseServer DatabaseServer;
+    private static readonly string[] _queries = new string[MaxBatch + 1];
+
+    public static string Query(int batchSize)
+    {
+        if (_queries[batchSize] != null)
+        {
+            return _queries[batchSize];
+        }
 
-        internal static readonly string[] Ids = Enumerable.Range(0, MaxBatch).Select(i => $"@Id_{i}").ToArray();
-        internal static readonly string[] Randoms = Enumerable.Range(0, MaxBatch).Select(i => $"@Random_{i}").ToArray();
+        var lastIndex = batchSize - 1;
 
-        private static string[] _queries = new string[MaxBatch + 1];
+        var sb = StringBuilderCache.Acquire();
 
-        public static string Query(int batchSize)
+        if (DatabaseServer == DatabaseServer.PostgreSql)
         {
-            if (_queries[batchSize] != null)
-            {
-                return _queries[batchSize];
-            }
-
-            var lastIndex = batchSize - 1;
-
-            var sb = StringBuilderCache.Acquire();
-
-            if (DatabaseServer == DatabaseServer.PostgreSql)
-            {
-                sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
-                Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
-                sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
-            }
-            else
-            {
-                Enumerable.Range(0, batchSize).ToList().ForEach(i => sb.Append($"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};"));
-            }
-
-            return _queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb);
+            sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
+            Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
+            sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
         }
+        else
+        {
+            Enumerable.Range(0, batchSize).ToList().ForEach(i => sb.Append($"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};"));
+        }
+
+        return _queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb);
     }
 }

+ 6 - 7
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/CachedWorld.cs

@@ -1,14 +1,13 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public sealed class CachedWorld
 {
-    public sealed class CachedWorld
-    {
-        public int Id { get; set; }
+    public int Id { get; set; }
 
-        public int RandomNumber { get; set; }
+    public int RandomNumber { get; set; }
 
-        public static implicit operator CachedWorld(World world) => new CachedWorld { Id = world.Id, RandomNumber = world.RandomNumber };
-    }
+    public static implicit operator CachedWorld(World world) => new CachedWorld { Id = world.Id, RandomNumber = world.RandomNumber };
 }

+ 11 - 14
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/Fortune.cs

@@ -1,25 +1,22 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
+namespace PlatformBenchmarks;
 
-namespace PlatformBenchmarks
+public readonly struct Fortune : IComparable<Fortune>, IComparable
 {
-    public readonly struct Fortune : IComparable<Fortune>, IComparable
+    public Fortune(int id, string message)
     {
-        public Fortune(int id, string message)
-        {
-            Id = id;
-            Message = message;
-        }
+        Id = id;
+        Message = message;
+    }
 
-        public int Id { get; }
+    public int Id { get; }
 
-        public string Message { get; }
+    public string Message { get; }
 
-        public int CompareTo(object obj) => throw new InvalidOperationException("The non-generic CompareTo should not be used");
+    public int CompareTo(object obj) => throw new InvalidOperationException("The non-generic CompareTo should not be used");
 
-        // Performance critical, using culture insensitive comparison
-        public int CompareTo(Fortune other) => string.CompareOrdinal(Message, other.Message);
-    }
+    // Performance critical, using culture insensitive comparison
+    public int CompareTo(Fortune other) => string.CompareOrdinal(Message, other.Message);
 }

+ 5 - 6
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/JsonMessage.cs

@@ -1,10 +1,9 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public struct JsonMessage
 {
-    public struct JsonMessage
-    {
-        public string message { get; set; }
-    }
-}
+    public string message { get; set; }
+}

+ 17 - 20
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/Random.cs

@@ -1,32 +1,29 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
 using System.Runtime.CompilerServices;
-using System.Threading;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public class ConcurrentRandom
 {
-    public class ConcurrentRandom
-    {
-        private static int nextSeed = 0;
+    private static int nextSeed = 0;
 
-        // Random isn't thread safe
-        [ThreadStatic]
-        private static Random _random;
+    // Random isn't thread safe
+    [ThreadStatic]
+    private static Random _random;
 
-        private static Random Random => _random ?? CreateRandom();
+    private static Random Random => _random ?? CreateRandom();
 
-        [MethodImpl(MethodImplOptions.NoInlining)]
-        private static Random CreateRandom()
-        {
-            _random = new Random(Interlocked.Increment(ref nextSeed));
-            return _random;
-        }
+    [MethodImpl(MethodImplOptions.NoInlining)]
+    private static Random CreateRandom()
+    {
+        _random = new Random(Interlocked.Increment(ref nextSeed));
+        return _random;
+    }
 
-        public int Next(int minValue, int maxValue)
-        {
-            return Random.Next(minValue, maxValue);
-        }
+    public int Next(int minValue, int maxValue)
+    {
+        return Random.Next(minValue, maxValue);
     }
 }

+ 6 - 7
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Data/World.cs

@@ -3,13 +3,12 @@
 
 using System.Runtime.InteropServices;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+[StructLayout(LayoutKind.Sequential, Size = 8)]
+public struct World
 {
-    [StructLayout(LayoutKind.Sequential, Size = 8)]
-    public struct World
-    {
-        public int Id { get; set; }
+    public int Id { get; set; }
 
-        public int RandomNumber { get; set; }
-    }
+    public int RandomNumber { get; set; }
 }

+ 43 - 45
frameworks/CSharp/aspnetcore/PlatformBenchmarks/DateHeader.cs

@@ -1,67 +1,65 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
 using System.Buffers.Text;
 using System.Diagnostics;
 using System.Text;
-using System.Threading;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+/// <summary>
+/// Manages the generation of the date header value.
+/// </summary>
+internal static class DateHeader
 {
-    /// <summary>
-    /// Manages the generation of the date header value.
-    /// </summary>
-    internal static class DateHeader
-    {
-        const int prefixLength = 8; // "\r\nDate: ".Length
-        const int dateTimeRLength = 29; // Wed, 14 Mar 2018 14:20:00 GMT
-        const int suffixLength = 2; // crlf
-        const int suffixIndex = dateTimeRLength + prefixLength;
+    const int prefixLength = 8; // "\r\nDate: ".Length
+    const int dateTimeRLength = 29; // Wed, 14 Mar 2018 14:20:00 GMT
+    const int suffixLength = 2; // crlf
+    const int suffixIndex = dateTimeRLength + prefixLength;
 
-        private static readonly Timer s_timer = new Timer((s) => {
-            SetDateValues(DateTimeOffset.UtcNow);
-        }, null, 1000, 1000);
+    private static readonly Timer s_timer = new((s) =>
+    {
+        SetDateValues(DateTimeOffset.UtcNow);
+    }, null, 1000, 1000);
 
-        private static byte[] s_headerBytesMaster = new byte[prefixLength + dateTimeRLength + 2 * suffixLength];
-        private static byte[] s_headerBytesScratch = new byte[prefixLength + dateTimeRLength + 2 * suffixLength];
+    private static byte[] s_headerBytesMaster = new byte[prefixLength + dateTimeRLength + 2 * suffixLength];
+    private static byte[] s_headerBytesScratch = new byte[prefixLength + dateTimeRLength + 2 * suffixLength];
 
-        static DateHeader()
-        {
-            var utf8 = Encoding.ASCII.GetBytes("\r\nDate: ").AsSpan();
+    static DateHeader()
+    {
+        var utf8 = Encoding.ASCII.GetBytes("\r\nDate: ").AsSpan();
 
-            utf8.CopyTo(s_headerBytesMaster);
-            utf8.CopyTo(s_headerBytesScratch);
-            s_headerBytesMaster[suffixIndex] = (byte)'\r';
-            s_headerBytesMaster[suffixIndex + 1] = (byte)'\n';
-            s_headerBytesMaster[suffixIndex + 2] = (byte)'\r';
-            s_headerBytesMaster[suffixIndex + 3] = (byte)'\n';
-            s_headerBytesScratch[suffixIndex] = (byte)'\r';
-            s_headerBytesScratch[suffixIndex + 1] = (byte)'\n';
-            s_headerBytesScratch[suffixIndex + 2] = (byte)'\r';
-            s_headerBytesScratch[suffixIndex + 3] = (byte)'\n';
+        utf8.CopyTo(s_headerBytesMaster);
+        utf8.CopyTo(s_headerBytesScratch);
+        s_headerBytesMaster[suffixIndex] = (byte)'\r';
+        s_headerBytesMaster[suffixIndex + 1] = (byte)'\n';
+        s_headerBytesMaster[suffixIndex + 2] = (byte)'\r';
+        s_headerBytesMaster[suffixIndex + 3] = (byte)'\n';
+        s_headerBytesScratch[suffixIndex] = (byte)'\r';
+        s_headerBytesScratch[suffixIndex + 1] = (byte)'\n';
+        s_headerBytesScratch[suffixIndex + 2] = (byte)'\r';
+        s_headerBytesScratch[suffixIndex + 3] = (byte)'\n';
 
-            SetDateValues(DateTimeOffset.UtcNow);
-            SyncDateTimer();
-        }
+        SetDateValues(DateTimeOffset.UtcNow);
+        SyncDateTimer();
+    }
 
-        public static void SyncDateTimer() => s_timer.Change(1000, 1000);
+    public static void SyncDateTimer() => s_timer.Change(1000, 1000);
 
-        public static ReadOnlySpan<byte> HeaderBytes => s_headerBytesMaster;
+    public static ReadOnlySpan<byte> HeaderBytes => s_headerBytesMaster;
 
-        private static void SetDateValues(DateTimeOffset value)
+    private static void SetDateValues(DateTimeOffset value)
+    {
+        lock (s_headerBytesScratch)
         {
-            lock (s_headerBytesScratch)
+            if (!Utf8Formatter.TryFormat(value, s_headerBytesScratch.AsSpan(prefixLength), out var written, 'R'))
             {
-                if (!Utf8Formatter.TryFormat(value, s_headerBytesScratch.AsSpan(prefixLength), out var written, 'R'))
-                {
-                    throw new Exception("date time format failed");
-                }
-                Debug.Assert(written == dateTimeRLength);
-                var temp = s_headerBytesMaster;
-                s_headerBytesMaster = s_headerBytesScratch;
-                s_headerBytesScratch = temp;
+                throw new Exception("date time format failed");
             }
+            Debug.Assert(written == dateTimeRLength);
+            var temp = s_headerBytesMaster;
+            s_headerBytesMaster = s_headerBytesScratch;
+            s_headerBytesScratch = temp;
         }
     }
 }

+ 14 - 15
frameworks/CSharp/aspnetcore/PlatformBenchmarks/HttpApplication.cs

@@ -4,26 +4,25 @@
 using System.Threading.Tasks;
 using Microsoft.AspNetCore.Connections;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public static class HttpApplicationConnectionBuilderExtensions
 {
-    public static class HttpApplicationConnectionBuilderExtensions
+    public static IConnectionBuilder UseHttpApplication<TConnection>(this IConnectionBuilder builder) where TConnection : IHttpConnection, new()
     {
-        public static IConnectionBuilder UseHttpApplication<TConnection>(this IConnectionBuilder builder) where TConnection : IHttpConnection, new()
-        {
-            return builder.Use(next => new HttpApplication<TConnection>().ExecuteAsync);
-        }
+        return builder.Use(next => new HttpApplication<TConnection>().ExecuteAsync);
     }
+}
 
-    public class HttpApplication<TConnection> where TConnection : IHttpConnection, new()
+public class HttpApplication<TConnection> where TConnection : IHttpConnection, new()
+{
+    public Task ExecuteAsync(ConnectionContext connection)
     {
-        public Task ExecuteAsync(ConnectionContext connection)
+        var httpConnection = new TConnection
         {
-            var httpConnection = new TConnection
-            {
-                Reader = connection.Transport.Input,
-                Writer = connection.Transport.Output
-            };
-            return httpConnection.ExecuteAsync();
-        }
+            Reader = connection.Transport.Input,
+            Writer = connection.Transport.Output
+        };
+        return httpConnection.ExecuteAsync();
     }
 }

+ 6 - 8
frameworks/CSharp/aspnetcore/PlatformBenchmarks/IHttpConnection.cs

@@ -2,15 +2,13 @@
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
 using System.IO.Pipelines;
-using System.Threading.Tasks;
 using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public interface IHttpConnection : IHttpHeadersHandler, IHttpRequestLineHandler
 {
-    public interface IHttpConnection : IHttpHeadersHandler, IHttpRequestLineHandler
-    {
-        PipeReader Reader { get; set; }
-        PipeWriter Writer { get; set; }
-        Task ExecuteAsync();
-    }
+    PipeReader Reader { get; set; }
+    PipeWriter Writer { get; set; }
+    Task ExecuteAsync();
 }

+ 3 - 2
frameworks/CSharp/aspnetcore/PlatformBenchmarks/PlatformBenchmarks.csproj

@@ -3,6 +3,7 @@
     <TargetFramework>net6.0</TargetFramework>
     <OutputType>Exe</OutputType>
     <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
+    <ImplicitUsings>enable</ImplicitUsings>
   </PropertyGroup>
   
   <PropertyGroup>
@@ -12,8 +13,8 @@
   </PropertyGroup>
   
   <ItemGroup>
-    <PackageReference Condition=" '$(DatabaseProvider)' == 'Npgsql' " Include="Npgsql" Version="6.0.0-rc.2" />
-    <PackageReference Condition=" '$(DatabaseProvider)' == 'MySqlConnector' " Include="MySqlConnector" Version="1.3.13" />
+    <PackageReference Condition=" '$(DatabaseProvider)' == 'Npgsql' " Include="Npgsql" Version="6.0.0" />
+    <PackageReference Condition=" '$(DatabaseProvider)' == 'MySqlConnector' " Include="MySqlConnector" Version="2.0.0" />
   </ItemGroup>
 
   <ItemGroup>

+ 46 - 52
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Program.cs

@@ -1,54 +1,49 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using System.Net;
 using System.Runtime.InteropServices;
-using System.Threading.Tasks;
-using Microsoft.AspNetCore.Hosting;
-using Microsoft.Extensions.Configuration;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+public class Program
 {
-    public class Program
-    {
-        public static string[] Args;
+    public static string[] Args;
 
-        public static async Task Main(string[] args)
-        {
-            Args = args;
+    public static async Task Main(string[] args)
+    {
+        Args = args;
 
-            Console.WriteLine(BenchmarkApplication.ApplicationName);
+        Console.WriteLine(BenchmarkApplication.ApplicationName);
 #if !DATABASE
-            Console.WriteLine(BenchmarkApplication.Paths.Plaintext);
-            Console.WriteLine(BenchmarkApplication.Paths.Json);
+        Console.WriteLine(BenchmarkApplication.Paths.Plaintext);
+        Console.WriteLine(BenchmarkApplication.Paths.Json);
 #else
             Console.WriteLine(BenchmarkApplication.Paths.Fortunes);
             Console.WriteLine(BenchmarkApplication.Paths.SingleQuery);
             Console.WriteLine(BenchmarkApplication.Paths.Updates);
             Console.WriteLine(BenchmarkApplication.Paths.MultipleQueries);
 #endif
-            DateHeader.SyncDateTimer();
+        DateHeader.SyncDateTimer();
 
-            var host = BuildWebHost(args);
-            var config = (IConfiguration)host.Services.GetService(typeof(IConfiguration));
-            BatchUpdateString.DatabaseServer = config.Get<AppSettings>().Database;
+        var host = BuildWebHost(args);
+        var config = (IConfiguration)host.Services.GetService(typeof(IConfiguration));
+        BatchUpdateString.DatabaseServer = config.Get<AppSettings>().Database;
 #if DATABASE
             await BenchmarkApplication.Db.PopulateCache();
 #endif
-            await host.RunAsync();
-        }
+        await host.RunAsync();
+    }
 
-        public static IWebHost BuildWebHost(string[] args)
-        {
-            var config = new ConfigurationBuilder()
-                .AddJsonFile("appsettings.json")
-                .AddEnvironmentVariables()
-                .AddEnvironmentVariables(prefix: "ASPNETCORE_")
-                .AddCommandLine(args)
-                .Build();
-
-            var appSettings = config.Get<AppSettings>();
+    public static IWebHost BuildWebHost(string[] args)
+    {
+        var config = new ConfigurationBuilder()
+            .AddJsonFile("appsettings.json")
+            .AddEnvironmentVariables()
+            .AddEnvironmentVariables(prefix: "ASPNETCORE_")
+            .AddCommandLine(args)
+            .Build();
+
+        var appSettings = config.Get<AppSettings>();
 #if DATABASE
             Console.WriteLine($"Database: {appSettings.Database}");
             Console.WriteLine($"ConnectionString: {appSettings.ConnectionString}");
@@ -64,33 +59,32 @@ namespace PlatformBenchmarks
             }
 #endif
 
-            var hostBuilder = new WebHostBuilder()
-                .UseBenchmarksConfiguration(config)
-                .UseKestrel((context, options) =>
+        var hostBuilder = new WebHostBuilder()
+            .UseBenchmarksConfiguration(config)
+            .UseKestrel((context, options) =>
+            {
+                var endPoint = context.Configuration.CreateIPEndPoint();
+
+                options.Listen(endPoint, builder =>
                 {
-                    var endPoint = context.Configuration.CreateIPEndPoint();
+                    builder.UseHttpApplication<BenchmarkApplication>();
+                });
+            })
+            .UseStartup<Startup>();
 
-                    options.Listen(endPoint, builder =>
-                    {
-                        builder.UseHttpApplication<BenchmarkApplication>();
-                    });
-                })
-                .UseStartup<Startup>();
+        hostBuilder.UseSockets(options =>
+        {
+            options.WaitForDataBeforeAllocatingBuffer = false;
 
-            hostBuilder.UseSockets(options =>
+            if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
             {
-                options.WaitForDataBeforeAllocatingBuffer = false;
-
-                if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
-                {
-                    options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
-                }
-            });
+                options.UnsafePreferInlineScheduling = Environment.GetEnvironmentVariable("DOTNET_SYSTEM_NET_SOCKETS_INLINE_COMPLETIONS") == "1";
+            }
+        });
 
 
-            var host = hostBuilder.Build();
+        var host = hostBuilder.Build();
 
-            return host;
-        }
+        return host;
     }
 }

+ 3 - 7
frameworks/CSharp/aspnetcore/PlatformBenchmarks/Startup.cs

@@ -1,15 +1,11 @@
 // Copyright (c) .NET Foundation. All rights reserved.
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 
-using System;
-using Microsoft.AspNetCore.Builder;
+namespace PlatformBenchmarks;
 
-namespace PlatformBenchmarks
+public class Startup
 {
-    public class Startup
+    public void Configure(IApplicationBuilder app)
     {
-        public void Configure(IApplicationBuilder app)
-        {
-        }
     }
 }

+ 36 - 38
frameworks/CSharp/aspnetcore/PlatformBenchmarks/StringBuilderCache.cs

@@ -1,59 +1,57 @@
 // Copyright (c) .NET Foundation. All rights reserved. 
 // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. 
 
-using System;
 using System.Text;
 
-namespace PlatformBenchmarks
+namespace PlatformBenchmarks;
+
+internal static class StringBuilderCache
 {
-    internal static class StringBuilderCache
-    {
-        private const int DefaultCapacity = 1386;
-        private const int MaxBuilderSize = DefaultCapacity * 3;
+    private const int DefaultCapacity = 1386;
+    private const int MaxBuilderSize = DefaultCapacity * 3;
 
-        [ThreadStatic]
-        private static StringBuilder t_cachedInstance;
+    [ThreadStatic]
+    private static StringBuilder t_cachedInstance;
 
-        /// <summary>Get a StringBuilder for the specified capacity.</summary>
-        /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks>
-        public static StringBuilder Acquire(int capacity = DefaultCapacity)
+    /// <summary>Get a StringBuilder for the specified capacity.</summary>
+    /// <remarks>If a StringBuilder of an appropriate size is cached, it will be returned and the cache emptied.</remarks>
+    public static StringBuilder Acquire(int capacity = DefaultCapacity)
+    {
+        if (capacity <= MaxBuilderSize)
         {
-            if (capacity <= MaxBuilderSize)
+            StringBuilder sb = t_cachedInstance;
+            if (capacity < DefaultCapacity)
             {
-                StringBuilder sb = t_cachedInstance;
-                if (capacity < DefaultCapacity)
-                {
-                    capacity = DefaultCapacity;
-                }
+                capacity = DefaultCapacity;
+            }
 
-                if (sb != null)
+            if (sb != null)
+            {
+                // Avoid stringbuilder block fragmentation by getting a new StringBuilder
+                // when the requested size is larger than the current capacity
+                if (capacity <= sb.Capacity)
                 {
-                    // Avoid stringbuilder block fragmentation by getting a new StringBuilder
-                    // when the requested size is larger than the current capacity
-                    if (capacity <= sb.Capacity)
-                    {
-                        t_cachedInstance = null;
-                        sb.Clear();
-                        return sb;
-                    }
+                    t_cachedInstance = null;
+                    sb.Clear();
+                    return sb;
                 }
             }
-            return new StringBuilder(capacity);
         }
+        return new StringBuilder(capacity);
+    }
 
-        public static void Release(StringBuilder sb)
+    public static void Release(StringBuilder sb)
+    {
+        if (sb.Capacity <= MaxBuilderSize)
         {
-            if (sb.Capacity <= MaxBuilderSize)
-            {
-                t_cachedInstance = sb;
-            }
+            t_cachedInstance = sb;
         }
+    }
 
-        public static string GetStringAndRelease(StringBuilder sb)
-        {
-            string result = sb.ToString();
-            Release(sb);
-            return result;
-        }
+    public static string GetStringAndRelease(StringBuilder sb)
+    {
+        string result = sb.ToString();
+        Release(sb);
+        return result;
     }
 }

+ 2 - 2
frameworks/CSharp/aspnetcore/aspcore-ado-my.dockerfile

@@ -1,9 +1,9 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 WORKDIR /app
 COPY PlatformBenchmarks .
 RUN dotnet publish -c Release -o out /p:DatabaseProvider=MySqlConnector
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 # Full PGO

+ 2 - 2
frameworks/CSharp/aspnetcore/aspcore-ado-pg-up.dockerfile

@@ -1,9 +1,9 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 WORKDIR /app
 COPY PlatformBenchmarks .
 RUN dotnet publish -c Release -o out /p:DatabaseProvider=Npgsql
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 # Full PGO

+ 2 - 2
frameworks/CSharp/aspnetcore/aspcore-ado-pg.dockerfile

@@ -1,9 +1,9 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 WORKDIR /app
 COPY PlatformBenchmarks .
 RUN dotnet publish -c Release -o out /p:DatabaseProvider=Npgsql
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 # Full PGO

+ 2 - 2
frameworks/CSharp/aspnetcore/aspcore-mvc-ado-my.dockerfile

@@ -1,9 +1,9 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 WORKDIR /app
 COPY Benchmarks .
 RUN dotnet publish -c Release -o out
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 # Full PGO

+ 2 - 2
frameworks/CSharp/aspnetcore/aspcore-mvc-ado-pg-up.dockerfile

@@ -1,9 +1,9 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 WORKDIR /app
 COPY Benchmarks .
 RUN dotnet publish -c Release -o out
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 # Full PGO

+ 2 - 2
frameworks/CSharp/aspnetcore/aspcore-mvc-ado-pg.dockerfile

@@ -1,9 +1,9 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 WORKDIR /app
 COPY Benchmarks .
 RUN dotnet publish -c Release -o out
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 # Full PGO

+ 2 - 2
frameworks/CSharp/aspnetcore/aspcore-mvc-dap-my.dockerfile

@@ -1,9 +1,9 @@
-FROM mcr.microsoft.com/dotnet/sdk:6.0.100-rc.2 AS build
+FROM mcr.microsoft.com/dotnet/sdk:6.0.100 AS build
 WORKDIR /app
 COPY Benchmarks .
 RUN dotnet publish -c Release -o out
 
-FROM mcr.microsoft.com/dotnet/aspnet:6.0.0-rc.2 AS runtime
+FROM mcr.microsoft.com/dotnet/aspnet:6.0.0 AS runtime
 ENV ASPNETCORE_URLS http://+:8080
 
 # Full PGO

Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików