Skip to content

Commit

Permalink
Merge pull request #46 from MarkCiliaVincenti/net9locking
Browse files Browse the repository at this point in the history
Improved .NET 9.0+ performance through System.Threading.Lock
  • Loading branch information
RRQM authored Dec 4, 2024
2 parents d048888 + 26adfbd commit 7526d72
Show file tree
Hide file tree
Showing 19 changed files with 34 additions and 21 deletions.
12 changes: 10 additions & 2 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,16 @@
<DefineConstants>ValueTask;Unsafe;SystemNetHttp;SystemMemory;SystemTextJson;AsyncEnumerable;DisposeAsync;DefaultInterfaceMethods</DefineConstants>
</PropertyGroup>


<ItemGroup Condition="!$(DefineConstants.Contains('SourceGenerator'))">
<PackageReference Include="Backport.System.Threading.Lock" Version="3.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>analyzers</IncludeAssets>
</PackageReference>
<Using Condition="$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net9.0'))" Alias="Lock" Include="System.Threading.Lock" />
<Using Condition="!$([MSBuild]::IsTargetFrameworkCompatible('$(TargetFramework)', 'net9.0'))" Alias="Lock" Include="Backport.System.Threading.Lock" />
<Using Alias="LockFactory" Include="Backport.System.Threading.LockFactory" />
</ItemGroup>
<Target Name="CopyNuGetPackage" AfterTargets="Pack" Condition="'$(Configuration)' == 'Release'">
<Copy SourceFiles="$(PackageOutputPath)\$(PackageId).$(PackageVersion).nupkg" DestinationFolder="D:\Nuget\local" />
</Target>
</Project>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ public WebSocketDmtpSessionClient()
private WebSocketDmtpService m_service;
private HttpContext m_httpContext;
private string m_id;
private readonly object m_locker = new object();
private readonly Lock m_locker = LockFactory.Create();

#endregion 字段

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>9.0</LangVersion>
<NoPackageAnalysis>true</NoPackageAnalysis>
<ImportDirectoryBuildProps>false</ImportDirectoryBuildProps>
<BaseOutputPath>bin</BaseOutputPath>
<GenerateDocumentationFile>False</GenerateDocumentationFile>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<SignAssembly>false</SignAssembly>
<DefineConstants>SourceGenerator</DefineConstants>
</PropertyGroup>

<ItemGroup>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ public class IntelligentDataQueue<T> : ConcurrentQueue<T> where T : IQueueData
{
private long m_actualSize;
private long m_maxSize;
private Lock m_lock = LockFactory.Create();

/// <summary>
/// 智能数据安全队列
Expand Down Expand Up @@ -175,7 +176,7 @@ public void Clear(Action<T> onClear)
/// <param name="item"></param>
public new void Enqueue(T item)
{
lock (this)
lock (m_lock)
{
var free = this.m_actualSize < this.m_maxSize;
if (this.Free != free)
Expand Down
4 changes: 3 additions & 1 deletion src/TouchSocket.Core/Core/SnowflakeIDGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ public class SnowflakeIdGenerator

private long m_lastTimestamp = -1L;

private Lock m_lock = LockFactory.Create();

static SnowflakeIdGenerator()
{
}
Expand Down Expand Up @@ -82,7 +84,7 @@ public SnowflakeIdGenerator(long workerId)
/// <returns></returns>
public long NextId()
{
lock (this)
lock (m_lock)
{
var timestamp = this.TimeGen();
if (this.m_lastTimestamp == timestamp)
Expand Down
2 changes: 1 addition & 1 deletion src/TouchSocket.Core/IO/FileIO/FilePool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ namespace TouchSocket.Core

public static partial class FilePool
{
private static readonly object s_locker = new object();
private static readonly Lock s_locker = LockFactory.Create();

private static readonly ConcurrentDictionary<string, FileStorage> m_pathStorage = new ConcurrentDictionary<string, FileStorage>();

Expand Down
2 changes: 1 addition & 1 deletion src/TouchSocket.Core/IO/FileIO/FileStorageWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ namespace TouchSocket.Core
public partial class FileStorageWriter : SafetyDisposableObject
{
private long m_position;

internal Lock m_lock = LockFactory.Create();

/// <summary>
/// 初始化FileStorageWriter的实例。
Expand Down
4 changes: 3 additions & 1 deletion src/TouchSocket.Core/Logger/ConsoleLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ namespace TouchSocket.Core
/// </summary>
public sealed class ConsoleLogger : LoggerBase
{
private static readonly Lock m_lock = LockFactory.Create();

static ConsoleLogger()
{
Default = new ConsoleLogger();
Expand Down Expand Up @@ -46,7 +48,7 @@ private ConsoleLogger()
/// <param name="exception"></param>
protected override void WriteLog(LogLevel logLevel, object source, string message, Exception exception)
{
lock (typeof(ConsoleLogger))
lock (m_lock)
{
Console.Write(DateTime.Now.ToString(this.DateTimeFormat));
Console.Write(" | ");
Expand Down
2 changes: 1 addition & 1 deletion src/TouchSocket.Core/Logger/FileLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ private void WriteLogStringToFile(string logString, LogLevel logLevel)

var writer = this.GetFileStorageWriter(dirPath);

lock (writer)
lock (writer.m_lock)
{
try
{
Expand Down
2 changes: 1 addition & 1 deletion src/TouchSocket.Core/Plugins/PluginManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ namespace TouchSocket.Core
/// </summary>
public sealed class PluginManager : DisposableObject, IPluginManager
{
private readonly object m_locker = new object();
private readonly Lock m_locker = LockFactory.Create();
private readonly IScopedResolver m_scopedResolver;
private Dictionary<Type, PluginInvokeLine> m_pluginMethods = new Dictionary<Type, PluginInvokeLine>();

Expand Down
2 changes: 1 addition & 1 deletion src/TouchSocket.Core/Threading/AsyncResetEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public class AsyncResetEvent : DisposableObject
{
private readonly bool m_autoReset;

private readonly object m_locker = new object();
private readonly Lock m_locker = LockFactory.Create();

private readonly Queue<TaskCompletionSource<bool>> m_waitQueue = new Queue<TaskCompletionSource<bool>>();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ public NamedPipeClientBase()
private ValueCounter m_receiveCounter;
private InternalReceiver m_receiver;
private SingleStreamDataHandlingAdapter m_dataHandlingAdapter;
private readonly object m_lockForAbort = new object();
private readonly Lock m_lockForAbort = LockFactory.Create();
#endregion 变量

#region 事件
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,8 @@ namespace TouchSocket.NamedPipe
public abstract class NamedPipeSessionClientBase : ResolverConfigObject, INamedPipeSession, INamedPipeListenableClient, IIdClient
{
#region 字段

private readonly object m_lockForAbort = new object();
private readonly SemaphoreSlim m_semaphoreSlimForSend = new SemaphoreSlim(1, 1);
private readonly Lock m_lockForAbort = LockFactory.Create();
private TouchSocketConfig m_config;
private SingleStreamDataHandlingAdapter m_dataHandlingAdapter;
private NamedPipeListenOption m_listenOption;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<LangVersion>9.0</LangVersion>
<NoPackageAnalysis>true</NoPackageAnalysis>
<ImportDirectoryBuildProps>false</ImportDirectoryBuildProps>
<BaseOutputPath>bin</BaseOutputPath>
<GenerateDocumentationFile>False</GenerateDocumentationFile>
<EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules>
<SignAssembly>false</SignAssembly>
<DefineConstants>SourceGenerator</DefineConstants>
</PropertyGroup>

<ItemGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/TouchSocket.Rpc/Common/CallContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ namespace TouchSocket.Rpc
/// </summary>
public abstract class CallContext : DependencyObject, ICallContext
{
private readonly object m_locker = new object();
private bool m_canceled;
private readonly Lock m_locker = LockFactory.Create();
private CancellationTokenSource m_tokenSource;

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ public SerialPortClientBase()

#region 变量

private readonly object m_lockForAbort = new object();
private readonly Lock m_lockForAbort = LockFactory.Create();
private readonly SemaphoreSlim m_semaphoreForConnect = new SemaphoreSlim(1, 1);
private SingleStreamDataHandlingAdapter m_dataHandlingAdapter;
private bool m_online;
Expand Down
3 changes: 2 additions & 1 deletion src/TouchSocket.WebApi/Plugins/WebApiParserPlugin.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ namespace TouchSocket.WebApi
[PluginOption(Singleton = true)]
public class WebApiParserPlugin : PluginBase, IHttpPlugin
{
private readonly Lock m_locker = LockFactory.Create();
private readonly Dictionary<RpcParameter, WebApiParameterInfo> m_pairsForParameterInfo = new Dictionary<RpcParameter, WebApiParameterInfo>();
private readonly IRpcServerProvider m_rpcServerProvider;

Expand Down Expand Up @@ -89,7 +90,7 @@ private WebApiParameterInfo GetParameterInfo(RpcParameter parameter)
return webApiParameterInfo;
}

lock (this.m_pairsForParameterInfo)
lock (this.m_locker)
{
if (!m_pairsForParameterInfo.ContainsKey(parameter))
{
Expand Down
2 changes: 1 addition & 1 deletion src/TouchSocket/Components/Tcp/TcpClientBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public TcpClientBase()

#region 变量

private readonly object m_lockForAbort = new object();
private readonly Lock m_lockForAbort = LockFactory.Create();
private readonly SemaphoreSlim m_semaphoreForConnect = new SemaphoreSlim(1, 1);
private readonly TcpCore m_tcpCore = new TcpCore();
private Task m_beginReceiveTask;
Expand Down
2 changes: 1 addition & 1 deletion src/TouchSocket/Components/Tcp/TcpSessionClientBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ protected TcpSessionClientBase()

#region 变量

private readonly object m_lockForAbort = new object();
private readonly Lock m_lockForAbort = LockFactory.Create();
private Task m_beginReceiveTask;
private SingleStreamDataHandlingAdapter m_dataHandlingAdapter;
private string m_id;
Expand Down

0 comments on commit 7526d72

Please sign in to comment.