diff --git a/TouchSocketVersion.props b/TouchSocketVersion.props index 3540cedb9..57f3adb47 100644 --- a/TouchSocketVersion.props +++ b/TouchSocketVersion.props @@ -1,7 +1,7 @@ - 4.0.0 + 4.0.1 diff --git a/src/TouchSocket.Core.DependencyInjection/Config/AspNetCoreConfigExtension.cs b/src/TouchSocket.Core.DependencyInjection/Config/AspNetCoreConfigExtension.cs index d2e408038..7ed1a1280 100644 --- a/src/TouchSocket.Core.DependencyInjection/Config/AspNetCoreConfigExtension.cs +++ b/src/TouchSocket.Core.DependencyInjection/Config/AspNetCoreConfigExtension.cs @@ -15,17 +15,18 @@ using TouchSocket.Core.AspNetCore; namespace TouchSocket.Core; + /// -/// AspNetCoreConfigExtension +/// 提供AspNetCore容器扩展方法。 /// public static class AspNetCoreConfigExtension { /// /// 使用作为容器。 /// - /// - /// - /// + /// 配置对象 + /// 服务集合 + /// 配置对象 public static TouchSocketConfig UseAspNetCoreContainer(this TouchSocketConfig config, IServiceCollection services) { config.SetRegistrator(new AspNetCoreContainer(services)); @@ -35,13 +36,102 @@ public static class AspNetCoreConfigExtension /// /// 配置容器。 /// - /// - /// - /// + /// 服务集合 + /// 配置操作 + /// 服务集合 public static IServiceCollection ConfigureContainer(this IServiceCollection services, Action action) { var container = new AspNetCoreContainer(services); action.Invoke(container); return services; } + + /// + /// 设置解析器。 + /// + /// 配置对象 + /// 服务提供者 + public static void SetResolver(this TouchSocketConfig config, IServiceProvider provider) + { + config.SetValue(TouchSocketCoreConfigExtension.ResolverProperty, new InternalResolver(provider)); + } + + #region InternalResolver + + /// + /// 内部解析器。 + /// + internal class InternalResolver : IResolver + { + private readonly IServiceProvider m_serviceProvider; + private readonly IKeyedServiceProvider m_keyedServiceProvider; + + /// + /// 初始化的新实例。 + /// + /// 服务提供者 + public InternalResolver(IServiceProvider serviceProvider) + { + this.m_serviceProvider = serviceProvider; + this.m_keyedServiceProvider = serviceProvider as IKeyedServiceProvider; + } + + /// + public IScopedResolver CreateScopedResolver() + { + return new InternalScopedResolver(this.m_serviceProvider.CreateScope()); + } + + /// + public object GetService(Type serviceType) + { + return this.m_serviceProvider.GetService(serviceType); + } + + /// + public object Resolve(Type fromType, object key) + { + return this.m_keyedServiceProvider.GetKeyedService(fromType, key); + } + + /// + public object Resolve(Type fromType) + { + return this.m_serviceProvider.GetService(fromType); + } + + /// + /// 内部作用域解析器。 + /// + private class InternalScopedResolver : DisposableObject, IScopedResolver + { + private readonly IServiceScope serviceScope; + private readonly InternalResolver resolver; + + /// + /// 初始化的新实例。 + /// + /// 服务作用域 + public InternalScopedResolver(IServiceScope serviceScope) + { + this.serviceScope = serviceScope; + this.resolver = new InternalResolver(serviceScope.ServiceProvider); + } + + /// + public IResolver Resolver => this.resolver; + + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + this.serviceScope.Dispose(); + } + base.Dispose(disposing); + } + } + } + + #endregion } \ No newline at end of file diff --git a/src/TouchSocket.Core/BytesPool/ByteBlock/ByteBlock.cs b/src/TouchSocket.Core/BytesPool/ByteBlock/ByteBlock.cs index b1cb0428d..11de779ae 100644 --- a/src/TouchSocket.Core/BytesPool/ByteBlock/ByteBlock.cs +++ b/src/TouchSocket.Core/BytesPool/ByteBlock/ByteBlock.cs @@ -45,6 +45,7 @@ public sealed class ByteBlock : IByteBlock public ByteBlock(Memory memory) { this.m_memory = memory; + this.m_length = memory.Length; } /// diff --git a/src/TouchSocket.Core/BytesPool/ByteBlock/ValueByteBlock.cs b/src/TouchSocket.Core/BytesPool/ByteBlock/ValueByteBlock.cs index c68040763..874ba2eac 100644 --- a/src/TouchSocket.Core/BytesPool/ByteBlock/ValueByteBlock.cs +++ b/src/TouchSocket.Core/BytesPool/ByteBlock/ValueByteBlock.cs @@ -44,6 +44,7 @@ public struct ValueByteBlock : IByteBlock public ValueByteBlock(Memory memory) { this.m_memory = memory; + this.m_length = memory.Length; } /// diff --git a/src/TouchSocket.Core/BytesPool/IBytesBuilder.cs b/src/TouchSocket.Core/BytesPool/IBytesBuilder.cs index 48deabae1..324cf6610 100644 --- a/src/TouchSocket.Core/BytesPool/IBytesBuilder.cs +++ b/src/TouchSocket.Core/BytesPool/IBytesBuilder.cs @@ -26,7 +26,7 @@ public interface IBytesBuilder int MaxLength { get; } /// - /// 构建对象到 + /// 构建对象到 /// /// 要构建的字节块对象引用。 void Build(ref TWriter writer) where TWriter : IBytesWriter diff --git a/src/TouchSocket.Core/DataAdapter/Test/SingleStreamDataAdapterTester2.cs b/src/TouchSocket.Core/DataAdapter/Test/SingleStreamDataAdapterTester2.cs index 329479b0b..1dd13fcd8 100644 --- a/src/TouchSocket.Core/DataAdapter/Test/SingleStreamDataAdapterTester2.cs +++ b/src/TouchSocket.Core/DataAdapter/Test/SingleStreamDataAdapterTester2.cs @@ -16,8 +16,10 @@ using System.IO.Pipelines; namespace TouchSocket.Core; /// -///单线程状况的流式数据处理适配器测试 +/// 单线程状况的流式数据处理适配器测试。 /// +/// 自定义数据处理适配器类型。 +/// 请求信息类型。 public class SingleStreamDataAdapterTester where TAdapter : CustomDataHandlingAdapter where TRequest : class, IRequestInfo @@ -32,12 +34,23 @@ public class SingleStreamDataAdapterTester /// /// Tcp数据处理适配器测试 /// + /// 自定义数据处理适配器实例。 + /// 接收回调委托。 public SingleStreamDataAdapterTester(TAdapter adapter, Action receivedCallBack = default) { this.m_adapter = adapter; this.m_receivedCallBack = receivedCallBack; } + /// + /// 异步运行测试。 + /// + /// 要发送的数据内存块。 + /// 测试发送次数。 + /// 预期接收次数。 + /// 每次写入的缓冲区长度。 + /// 取消操作的令牌。 + /// 返回测试所用的时间。 public async Task RunAsync(ReadOnlyMemory memory, int testCount, int expectedCount, int bufferLength, CancellationToken cancellationToken) { this.m_count = 0; diff --git a/src/TouchSocket.Core/DataAdapter/Test/UdpDataAdapterTester.cs b/src/TouchSocket.Core/DataAdapter/Test/UdpDataAdapterTester.cs index 7ae1613f0..dc9b9230b 100644 --- a/src/TouchSocket.Core/DataAdapter/Test/UdpDataAdapterTester.cs +++ b/src/TouchSocket.Core/DataAdapter/Test/UdpDataAdapterTester.cs @@ -13,10 +13,14 @@ namespace TouchSocket.Core; /// -/// Udp数据处理适配器测试 +/// Udp数据处理适配器测试。 /// public class UdpDataAdapterTester : MultithreadingDataAdapterTester { + /// + /// 初始化 类的新实例。 + /// + /// 多线程数量。 protected UdpDataAdapterTester(int multiThread) : base(multiThread) { } diff --git a/src/TouchSocket.Core/DataAdapter/Udp/UdpDataHandlingAdapter.cs b/src/TouchSocket.Core/DataAdapter/Udp/UdpDataHandlingAdapter.cs index 3a36510c5..a77fc5ff1 100644 --- a/src/TouchSocket.Core/DataAdapter/Udp/UdpDataHandlingAdapter.cs +++ b/src/TouchSocket.Core/DataAdapter/Udp/UdpDataHandlingAdapter.cs @@ -15,7 +15,7 @@ using System.Net; namespace TouchSocket.Core; /// -/// Udp数据处理适配器 +/// Udp数据处理适配器。 /// public abstract class UdpDataHandlingAdapter : DataHandlingAdapter { @@ -23,38 +23,32 @@ public abstract class UdpDataHandlingAdapter : DataHandlingAdapter public override bool CanSendRequestInfo => false; /// - /// 当接收数据处理完成后,回调该函数执行接收 + /// 当接收数据处理完成后,回调该函数执行接收。 /// public Func, IRequestInfo, Task> ReceivedCallBack { get; set; } /// - /// 当接收数据处理完成后,异步回调该函数执行发送 + /// 当接收数据处理完成后,异步回调该函数执行发送。 /// public Func, CancellationToken, Task> SendCallBackAsync { get; set; } /// /// 收到数据的切入点,该方法由框架自动调用。 /// - /// - /// + /// 远程端点。 + /// 接收到的数据。 public Task ReceivedInputAsync(EndPoint remoteEndPoint, ReadOnlyMemory memory) { return this.PreviewReceivedAsync(remoteEndPoint, memory); } - #region SendInputAsync - /// /// 异步发送输入数据。 /// /// 要发送数据的端点。 /// 包含要发送的数据的只读内存。 - /// 可取消令箭 + /// 可取消令箭。 /// 返回一个任务,表示发送操作。 - /// - /// 此方法是一个异步操作,用于向指定的端点发送输入数据。 - /// 它使用PreviewSendAsync方法来执行实际的发送操作。 - /// public Task SendInputAsync(EndPoint endPoint, ReadOnlyMemory memory, CancellationToken cancellationToken) { return this.PreviewSendAsync(endPoint, memory, cancellationToken); @@ -63,22 +57,21 @@ public abstract class UdpDataHandlingAdapter : DataHandlingAdapter /// /// 发送数据的切入点,该方法由框架自动调用。 /// - /// - /// - /// 可取消令箭 + /// 目标端点。 + /// 请求信息。 + /// 可取消令箭。 public Task SendInputAsync(EndPoint endPoint, IRequestInfo requestInfo, CancellationToken cancellationToken) { return this.PreviewSendAsync(endPoint, requestInfo, cancellationToken); } - #endregion SendInputAsync /// - /// 处理已经经过预先处理后的数据 + /// 处理已经经过预先处理后的数据。 /// - /// 远程端点,标识数据来源 - /// 接收到的二进制数据块 - /// 解析后的请求信息 - /// 一个异步任务,代表处理过程 + /// 远程端点,标识数据来源。 + /// 接收到的二进制数据块。 + /// 解析后的请求信息。 + /// 一个异步任务,代表处理过程。 protected Task GoReceived(EndPoint remoteEndPoint, ReadOnlyMemory memory, IRequestInfo requestInfo) { // 调用接收回调,继续处理接收到的数据 @@ -86,32 +79,33 @@ public abstract class UdpDataHandlingAdapter : DataHandlingAdapter } /// - /// 发送已经经过预先处理后的数据 + /// 发送已经经过预先处理后的数据。 /// - /// 目标端点,表示数据发送的目的地址 - /// 已经经过预先处理的字节数据,以 ReadOnlyMemory 方式传递以提高性能 - /// 可取消令箭 - /// 返回一个 Task 对象,表示异步操作的完成 + /// 目标端点,表示数据发送的目的地址。 + /// 已经经过预先处理的字节数据。 + /// 可取消令箭。 + /// 返回一个任务,表示异步操作的完成。 protected Task GoSendAsync(EndPoint endPoint, ReadOnlyMemory memory, CancellationToken cancellationToken) { return this.SendCallBackAsync.Invoke(endPoint, memory, cancellationToken); } + /// - /// 当接收到数据后预先处理数据,然后调用处理数据 + /// 在接收数据前预先处理数据。 /// - /// - /// + /// 远程端点。 + /// 接收到的数据。 protected virtual async Task PreviewReceivedAsync(EndPoint remoteEndPoint, ReadOnlyMemory memory) { await this.GoReceived(remoteEndPoint, memory, default).ConfigureAwait(EasyTask.ContinueOnCapturedContext); } /// - /// 当发送数据前预先处理数据 + /// 当发送数据前预先处理数据。 /// - /// - /// - /// 可取消令箭 + /// 目标端点。 + /// 请求信息。 + /// 可取消令箭。 protected virtual async Task PreviewSendAsync(EndPoint endPoint, IRequestInfo requestInfo, CancellationToken cancellationToken) { ThrowHelper.ThrowIfNull(requestInfo, nameof(requestInfo)); @@ -135,8 +129,8 @@ public abstract class UdpDataHandlingAdapter : DataHandlingAdapter /// /// 数据发送的目标端点。 /// 待发送的字节数据内存。 - /// 可取消令箭 - /// 一个表示异步操作完成的 对象。 + /// 可取消令箭。 + /// 一个表示异步操作完成的任务。 protected virtual Task PreviewSendAsync(EndPoint endPoint, ReadOnlyMemory memory, CancellationToken cancellationToken) { return this.GoSendAsync(endPoint, memory, cancellationToken); @@ -145,12 +139,10 @@ public abstract class UdpDataHandlingAdapter : DataHandlingAdapter /// protected override void Reset() { - } /// protected override void SafetyDispose(bool disposing) { - } } \ No newline at end of file diff --git a/src/TouchSocket.Core/Extensions/SystemExtension.cs b/src/TouchSocket.Core/Extensions/SystemExtension.cs index d03ce9c46..676f0ecff 100644 --- a/src/TouchSocket.Core/Extensions/SystemExtension.cs +++ b/src/TouchSocket.Core/Extensions/SystemExtension.cs @@ -22,7 +22,7 @@ using System.Runtime.InteropServices; namespace TouchSocket.Core; /// -/// 为System提供扩展。 +/// 为 提供扩展方法。 /// public static class SystemExtension { @@ -85,11 +85,11 @@ public static class SystemExtension /// - /// 获取枚举成员上绑定的指定类型的自定义属性 + /// 获取枚举成员上绑定的指定类型的自定义属性。 /// - /// 枚举对象 - /// 要获取的属性类型 - /// 指定类型的自定义属性 + /// 要获取的属性类型。 + /// 枚举对象。 + /// 指定类型的自定义属性。 public static T GetAttribute(this Enum enumObj) where T : Attribute { // 获取枚举对象的类型 @@ -110,13 +110,12 @@ public static class SystemExtension #region SetBit /// - /// 对于给定的无符号长整型数值,设置指定索引位置的位值为指定的布尔值。 + /// 设置无符号长整型数值的指定位。 /// /// 原始数值。 - /// 位索引,范围为0到63。 - /// 要设置的位值(true为1,false为0)。 + /// 位索引。 + /// 要设置的位值。 /// 修改后的数值。 - /// 当索引值不在有效范围内时抛出异常。 public static ulong SetBit(this ulong value, int index, bool bitvalue) { var accessor = new BitAccessor(ref value); @@ -173,7 +172,7 @@ public static class SystemExtension #region GetBit /// - /// 获取无符号长整型数值中的指定位置的位是否为1。 + /// 获取无符号长整型数值的指定位。 /// /// 要检查的无符号长整型数值。 /// 要检查的位的位置,从0到63。 @@ -228,13 +227,26 @@ public static class SystemExtension #region Byte[] /// - /// 字节数组转16进制字符 + /// 将字节数组转换为十六进制字符串。 /// - /// - /// - /// - /// - /// + /// 字节数组。 + /// 分隔符。 + /// 十六进制字符串。 + public static string ByBytesToHexString(this byte[] buffer, string split = default) + { + return string.IsNullOrEmpty(split) + ? BitConverter.ToString(buffer).Replace("-", string.Empty) + : BitConverter.ToString(buffer).Replace("-", split); + } + + /// + /// 将字节缓冲区转换为十六进制字符串。 + /// + /// 要转换的字节缓冲区。 + /// 缓冲区的起始索引。 + /// 要转换的字节数。 + /// 可选参数,用于指定分隔符,默认为空。 + /// 转换后的十六进制字符串。 public static string ByBytesToHexString(this byte[] buffer, int offset, int length, string split = default) { return string.IsNullOrEmpty(split) @@ -242,17 +254,6 @@ public static class SystemExtension : BitConverter.ToString(buffer, offset, length).Replace("-", split); } - - /// - /// 将字节缓冲区转换为十六进制字符串。 - /// - /// 要转换的字节缓冲区。 - /// 可选参数,用于指定分隔符,默认为空。 - /// 转换后的十六进制字符串。 - public static string ByBytesToHexString(this byte[] buffer, string split = default) - { - return ByBytesToHexString(buffer, 0, buffer.Length, split); - } /// /// 索引第一个包含数组的索引位置,例如:在{0,1,2,3,1,2,3}中索引{2,3},则返回3。 /// 如果目标数组为或长度为0,则直接返回offset的值 @@ -1000,6 +1001,12 @@ public static class SystemExtension } } + /// + /// 异步读取流中的所有字节。 + /// + /// 流。 + /// 取消令牌。 + /// 字节数组。 public static async Task ReadAllToByteArrayAsync(this Stream stream, CancellationToken cancellationToken) { using (var memoryStream = new MemoryStream()) diff --git a/src/TouchSocket.Core/IO/FileIO/FileStorage.cs b/src/TouchSocket.Core/IO/FileIO/FileStorage.cs index 309c20074..d4e77d357 100644 --- a/src/TouchSocket.Core/IO/FileIO/FileStorage.cs +++ b/src/TouchSocket.Core/IO/FileIO/FileStorage.cs @@ -12,7 +12,7 @@ namespace TouchSocket.Core; /// -/// 简化版文件存储器 +/// 简化版文件存储器。 /// public sealed partial class FileStorage : IDisposable { @@ -21,6 +21,10 @@ public sealed partial class FileStorage : IDisposable internal int m_referenceCount; private bool m_disposed; + /// + /// 初始化 类的新实例。 + /// + /// 文件路径。 internal FileStorage(string path) { this.Path = path; @@ -28,12 +32,12 @@ public sealed partial class FileStorage : IDisposable } /// - /// 文件路径 + /// 获取文件路径。 /// public string Path { get; } /// - /// 文件长度 + /// 获取文件长度。 /// public long Length { @@ -52,14 +56,25 @@ public sealed partial class FileStorage : IDisposable } } + /// + /// 获取一个值,指示是否可以读取文件。 + /// public bool CanRead => this.m_fileStream.CanRead; + + /// + /// 获取一个值,指示是否可以查找文件位置。 + /// public bool CanSeek => this.m_fileStream.CanSeek; + + /// + /// 获取一个值,指示是否可以写入文件。 + /// public bool CanWrite => this.m_fileStream.CanWrite; /// - /// 设置文件长度 + /// 设置文件长度。 /// - /// 新长度 + /// 新长度。 public void SetLength(long length) { this.m_semaphore.Wait(); @@ -75,7 +90,7 @@ public sealed partial class FileStorage : IDisposable } /// - /// 刷新缓冲区 + /// 刷新缓冲区。 /// public void Flush() { @@ -142,13 +157,13 @@ public sealed partial class FileStorage : IDisposable } /// - /// 读取数据 + /// 读取数据。 /// - /// 读取位置 - /// 缓冲区 - /// 缓冲区偏移量 - /// 读取字节数 - /// 实际读取的字节数 + /// 读取位置。 + /// 缓冲区。 + /// 缓冲区偏移量。 + /// 读取字节数。 + /// 实际读取的字节数。 public int Read(long position, byte[] buffer, int offset, int count) { this.m_semaphore.Wait(); @@ -165,12 +180,12 @@ public sealed partial class FileStorage : IDisposable } /// - /// 写入数据 + /// 写入数据。 /// - /// 写入位置 - /// 数据 - /// 缓冲区偏移量 - /// 写入字节数 + /// 写入位置。 + /// 数据。 + /// 缓冲区偏移量。 + /// 写入字节数。 public void Write(long position, byte[] buffer, int offset, int count) { this.m_semaphore.Wait(); @@ -187,12 +202,12 @@ public sealed partial class FileStorage : IDisposable } /// - /// 异步读取数据 + /// 异步读取数据。 /// - /// 读取位置 - /// 缓冲区 - /// 取消令牌 - /// 实际读取的字节数 + /// 读取位置。 + /// 缓冲区。 + /// 取消令牌。 + /// 实际读取的字节数。 public async Task ReadAsync(long position, Memory memory, CancellationToken cancellationToken = default) { await this.m_semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -209,11 +224,11 @@ public sealed partial class FileStorage : IDisposable } /// - /// 异步写入数据 + /// 异步写入数据。 /// - /// 写入位置 - /// 数据 - /// 取消令牌 + /// 写入位置。 + /// 数据。 + /// 取消令牌。 public async Task WriteAsync(long position, ReadOnlyMemory memory, CancellationToken cancellationToken = default) { await this.m_semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -230,9 +245,9 @@ public sealed partial class FileStorage : IDisposable } /// - /// 异步刷新缓冲区 + /// 异步刷新缓冲区。 /// - /// 取消令牌 + /// 取消令牌。 public async Task FlushAsync(CancellationToken cancellationToken = default) { await this.m_semaphore.WaitAsync(cancellationToken).ConfigureAwait(false); @@ -247,13 +262,12 @@ public sealed partial class FileStorage : IDisposable } } - /// - /// 读取数据 + /// 读取数据。 /// - /// 读取位置 - /// 缓冲区 - /// 实际读取的字节数 + /// 读取位置。 + /// 缓冲区。 + /// 实际读取的字节数。 public int Read(long position, Span buffer) { this.m_semaphore.Wait(); @@ -270,10 +284,10 @@ public sealed partial class FileStorage : IDisposable } /// - /// 写入数据 + /// 写入数据。 /// - /// 写入位置 - /// 数据 + /// 写入位置。 + /// 数据。 public void Write(long position, ReadOnlySpan buffer) { this.m_semaphore.Wait(); diff --git a/src/TouchSocket.Core/Reflection/Field.cs b/src/TouchSocket.Core/Reflection/Field.cs index dd9cd6490..0ee15637f 100644 --- a/src/TouchSocket.Core/Reflection/Field.cs +++ b/src/TouchSocket.Core/Reflection/Field.cs @@ -15,6 +15,9 @@ using System.Reflection; namespace TouchSocket.Core; +/// +/// 表示一个字段的封装。 +/// public sealed class Field { /// @@ -30,7 +33,7 @@ public sealed class Field /// /// 字段 /// - /// 字段信息 + /// 字段信息。 public Field(FieldInfo fieldInfo) { this.Info = fieldInfo; @@ -44,37 +47,37 @@ public sealed class Field } /// - /// 获取字段信息 + /// 获取字段信息。 /// public FieldInfo Info { get; } /// - /// 从类型的字段获取字段 + /// 从类型的字段获取字段。 /// - /// 类型 - /// + /// 类型。 + /// 字段数组。 public static Field[] GetFields([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields)] Type type) { return type.GetFields().Select(p => new Field(p)).ToArray(); } /// - /// 获取字段的值 + /// 获取字段的值。 /// - /// 实例 - /// - /// + /// 实例。 + /// 字段的值。 + /// 当字段不支持获取值时抛出。 public object GetValue(object instance) { return this.m_geter == null ? throw new NotSupportedException() : this.m_geter.Invoke(instance); } /// - /// 设置字段的值 + /// 设置字段的值。 /// - /// 实例 - /// 值 - /// + /// 实例。 + /// 值。 + /// 当字段不支持设置值时抛出。 public void SetValue(object instance, object value) { if (this.m_seter == null) diff --git a/src/TouchSocket.Core/Serialization/FastBinary/FastBinaryFormatter.cs b/src/TouchSocket.Core/Serialization/FastBinary/FastBinaryFormatter.cs index 62144a7ad..9bca1df96 100644 --- a/src/TouchSocket.Core/Serialization/FastBinary/FastBinaryFormatter.cs +++ b/src/TouchSocket.Core/Serialization/FastBinary/FastBinaryFormatter.cs @@ -10,6 +10,7 @@ // 感谢您的下载和使用 //------------------------------------------------------------------------------ +using System.Buffers; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; @@ -133,11 +134,11 @@ public static class FastBinaryFormatter [RequiresUnreferencedCode("此方法可能会使用反射构建访问器,与剪裁不兼容。如果已使用源生成上下文,可以忽略此警告。")] public static byte[] SerializeToBytes<[DynamicallyAccessedMembers(AOT.FastBinaryFormatter)] T>(in T graph, FastSerializerContext serializerContext = null) { - var byteBlock = new ValueByteBlock(1024 * 64); + var byteBlock = new SegmentedBytesWriter(); try { Serialize(ref byteBlock, graph, serializerContext); - return byteBlock.ToArray(); + return byteBlock.Sequence.ToArray(); } finally { @@ -339,8 +340,8 @@ public static class FastBinaryFormatter [RequiresUnreferencedCode("此方法可能会使用反射构建访问器,与剪裁不兼容。如果已使用源生成上下文,可以忽略此警告。")] public static T Deserialize<[DynamicallyAccessedMembers(AOT.FastBinaryFormatter)] T>(byte[] bytes, FastSerializerContext serializerContext = null) { - var byteBlock = new ValueByteBlock(bytes); - return Deserialize(ref byteBlock, serializerContext); + var reader = new BytesReader(bytes); + return Deserialize(ref reader, serializerContext); } /// @@ -406,11 +407,9 @@ public static class FastBinaryFormatter // 复杂类型:先读体长度 var len = ReaderExtension.ReadValue(ref reader); var serializeObj = serializerContext.GetSerializeObject(type); - if (serializeObj.Converter != null) - { - return serializeObj.Converter.Read(ref reader, type); - } - return DeserializeClass(type, serializeObj, ref reader, len, serializerContext); + return serializeObj.Converter != null + ? serializeObj.Converter.Read(ref reader, type) + : DeserializeClass(type, serializeObj, ref reader, len, serializerContext); } [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "数组元素类型已通过DynamicallyAccessedMembers标记保证存在")] diff --git a/src/TouchSocket.Core/Serialization/SerializerFormatter/XmlStringToClassSerializerFormatter.cs b/src/TouchSocket.Core/Serialization/SerializerFormatter/XmlStringToClassSerializerFormatter.cs index c8bc0d975..a4cb27dd9 100644 --- a/src/TouchSocket.Core/Serialization/SerializerFormatter/XmlStringToClassSerializerFormatter.cs +++ b/src/TouchSocket.Core/Serialization/SerializerFormatter/XmlStringToClassSerializerFormatter.cs @@ -19,6 +19,7 @@ namespace TouchSocket.Core; /// /// [RequiresUnreferencedCode("Members from deserialized types may be trimmed if not referenced directly")] +[RequiresDynamicCode("XML serializer relies on dynamic code generation which is not available with Ahead of Time compilation")] public class XmlStringToClassSerializerFormatter : ISerializerFormatter { /// diff --git a/src/TouchSocket.Http/WebSockets/Plugins/WebSocketFeatureOptions.cs b/src/TouchSocket.Http/WebSockets/Plugins/WebSocketFeatureOptions.cs index 3c236791e..0fd43bd6c 100644 --- a/src/TouchSocket.Http/WebSockets/Plugins/WebSocketFeatureOptions.cs +++ b/src/TouchSocket.Http/WebSockets/Plugins/WebSocketFeatureOptions.cs @@ -36,30 +36,25 @@ public sealed class WebSocketFeatureOptions /// 设置是否自动处理Close报文 /// /// 是否自动处理Close报文 - /// 返回当前配置选项实例,支持链式调用 - public WebSocketFeatureOptions SetAutoClose(bool autoClose) + public void SetAutoClose(bool autoClose) { this.AutoClose = autoClose; - return this; } /// /// 设置是否自动回应Ping报文 /// /// 是否自动回应Ping报文 - /// 返回当前配置选项实例,支持链式调用 - public WebSocketFeatureOptions SetAutoPong(bool autoPong) + public void SetAutoPong(bool autoPong) { this.AutoPong = autoPong; - return this; } /// /// 设置WebSocket连接的URL路径 /// /// WebSocket连接路径,如果为null或空则表示所有连接都解释为WS - /// 返回当前配置选项实例,支持链式调用 - public WebSocketFeatureOptions SetUrl(string url = "/ws") + public void SetUrl(string url = "/ws") { if (url.IsNullOrEmpty()) { @@ -72,22 +67,15 @@ public sealed class WebSocketFeatureOptions this.SetVerifyConnection((client, context) => { - if (url == "/" || context.Request.UrlEquals(url)) - { - return true; - } - - return false; + return url == "/" || context.Request.UrlEquals(url); }); - return this; } /// /// 设置验证连接的同步方法 /// /// 验证连接的同步委托 - /// 返回当前配置选项实例,支持链式调用 - public WebSocketFeatureOptions SetVerifyConnection(Func verifyConnection) + public void SetVerifyConnection(Func verifyConnection) { ThrowHelper.ThrowIfNull(verifyConnection, nameof(verifyConnection)); @@ -96,18 +84,15 @@ public sealed class WebSocketFeatureOptions await EasyTask.CompletedTask.ConfigureAwait(EasyTask.ContinueOnCapturedContext); return verifyConnection.Invoke(client, context); }; - return this; } /// /// 设置验证连接的异步方法 /// /// 验证连接的异步委托 - /// 返回当前配置选项实例,支持链式调用 - public WebSocketFeatureOptions SetVerifyConnection(Func> verifyConnection) + public void SetVerifyConnection(Func> verifyConnection) { ThrowHelper.ThrowIfNull(verifyConnection, nameof(verifyConnection)); this.VerifyConnection = verifyConnection; - return this; } } \ No newline at end of file diff --git a/src/TouchSocket.Mqtt/Actors/MqttActor.cs b/src/TouchSocket.Mqtt/Actors/MqttActor.cs index bfb985f9c..c9b328a9f 100644 --- a/src/TouchSocket.Mqtt/Actors/MqttActor.cs +++ b/src/TouchSocket.Mqtt/Actors/MqttActor.cs @@ -14,6 +14,7 @@ using TouchSocket.Sockets; namespace TouchSocket.Mqtt; +/// public abstract class MqttActor : DisposableObject, IOnlineClient { #region 字段 @@ -24,11 +25,7 @@ public abstract class MqttActor : DisposableObject, IOnlineClient #endregion 字段 - public MqttActor() - { - - } - + /// protected override void Dispose(bool disposing) { if (this.DisposedValue) @@ -44,6 +41,7 @@ public abstract class MqttActor : DisposableObject, IOnlineClient } } + /// protected virtual Task PublishMessageArrivedAsync(MqttArrivedMessage message) { if (this.MessageArrived != null) @@ -59,18 +57,23 @@ public abstract class MqttActor : DisposableObject, IOnlineClient #region 属性 + /// public string Id { get; protected set; } + /// public bool Online { get; protected set; } + /// public CancellationTokenSource TokenSource => this.m_tokenSource; + /// public WaitHandlePool WaitHandlePool => this.m_waitHandlePool; #endregion 属性 #region Publish + /// public Task PublishAsync(MqttPublishMessage message, CancellationToken cancellationToken) { switch (message.QosLevel) @@ -137,6 +140,7 @@ public abstract class MqttActor : DisposableObject, IOnlineClient #region InputMqttMessage + /// public async Task InputMqttMessageAsync(MqttMessage mqttMessage, CancellationToken cancellationToken) { switch (mqttMessage) @@ -385,17 +389,24 @@ public abstract class MqttActor : DisposableObject, IOnlineClient #region 委托 + /// public Func Closing { get; set; } + /// public Func Connected { get; set; } + /// public Func Connecting { get; set; } + /// public Func MessageArrived { get; set; } + /// public Func OutputSendAsync { get; set; } + /// public MqttProtocolVersion Version { get; protected set; } #endregion 委托 #region 委托方法 + /// protected async Task ProtectedMqttOnClosing(MqttDisconnectMessage message) { if (this.Closing != null) @@ -404,6 +415,7 @@ public abstract class MqttActor : DisposableObject, IOnlineClient } } + /// protected async Task ProtectedMqttOnConnected(MqttConnectedEventArgs e) { if (this.Connected != null) @@ -412,6 +424,7 @@ public abstract class MqttActor : DisposableObject, IOnlineClient } } + /// protected async Task ProtectedMqttOnConnecting(MqttConnectingEventArgs e) { if (this.Connecting != null) @@ -420,6 +433,7 @@ public abstract class MqttActor : DisposableObject, IOnlineClient } } + /// protected Task ProtectedOutputSendAsync(MqttMessage message, CancellationToken cancellationToken) { if (message.MessageType == MqttMessageType.Connect) diff --git a/src/TouchSocket.Mqtt/Actors/MqttClientActor.cs b/src/TouchSocket.Mqtt/Actors/MqttClientActor.cs index ffd4c130c..a1632218d 100644 --- a/src/TouchSocket.Mqtt/Actors/MqttClientActor.cs +++ b/src/TouchSocket.Mqtt/Actors/MqttClientActor.cs @@ -17,6 +17,11 @@ public sealed class MqttClientActor : MqttActor private TaskCompletionSource m_waitForConnect; private readonly WaitDataAsync m_waitForPing = new(); + /// + /// 异步断开连接。 + /// + /// 取消令牌。 + /// 任务。 public async Task DisconnectAsync(CancellationToken cancellationToken) { if (!this.Online) @@ -36,6 +41,11 @@ public sealed class MqttClientActor : MqttActor } } + /// + /// 异步发送PING消息。 + /// + /// 取消令牌。 + /// 操作结果。 public async ValueTask PingAsync(CancellationToken cancellationToken) { var contentForAck = new MqttPingReqMessage(); @@ -54,8 +64,12 @@ public sealed class MqttClientActor : MqttActor }; } - #region 连接 - + /// + /// 异步连接。 + /// + /// 连接消息。 + /// 取消令牌。 + /// 连接确认消息。 public async Task ConnectAsync(MqttConnectMessage message, CancellationToken cancellationToken) { this.m_waitForConnect = new TaskCompletionSource(); @@ -66,32 +80,35 @@ public sealed class MqttClientActor : MqttActor return connAckMessage; } - #endregion 连接 - #region 重写 + /// protected override Task InputMqttConnAckMessageAsync(MqttConnAckMessage message, CancellationToken cancellationToken) { this.m_waitForConnect?.SetResult(message); return EasyTask.CompletedTask; } + /// protected override Task InputMqttConnectMessageAsync(MqttConnectMessage message, CancellationToken cancellationToken) { throw ThrowHelper.CreateNotSupportedException($"遇到无法处理的数据报文,Message={message}"); } + /// protected override Task InputMqttPingRespMessageAsync(MqttPingRespMessage message, CancellationToken cancellationToken) { this.m_waitForPing.Set(message); return EasyTask.CompletedTask; } + /// protected override Task InputMqttSubscribeMessageAsync(MqttSubscribeMessage message, CancellationToken cancellationToken) { throw ThrowHelper.CreateNotSupportedException($"遇到无法处理的数据报文,Message={message}"); } + /// protected override Task InputMqttUnsubscribeMessageAsync(MqttUnsubscribeMessage message, CancellationToken cancellationToken) { throw ThrowHelper.CreateNotSupportedException($"遇到无法处理的数据报文,Message={message}"); @@ -99,6 +116,12 @@ public sealed class MqttClientActor : MqttActor #endregion 重写 + /// + /// 异步订阅。 + /// + /// 订阅消息。 + /// 取消令牌。 + /// 订阅确认消息。 public async Task SubscribeAsync(MqttSubscribeMessage message, CancellationToken cancellationToken = default) { using (var waitDataAsync = this.WaitHandlePool.GetWaitDataAsync(message)) @@ -112,6 +135,12 @@ public sealed class MqttClientActor : MqttActor } } + /// + /// 异步取消订阅。 + /// + /// 取消订阅消息。 + /// 取消令牌。 + /// 取消订阅确认消息。 public async Task UnsubscribeAsync(MqttUnsubscribeMessage message, CancellationToken cancellationToken = default) { using (var waitDataAsync = this.WaitHandlePool.GetWaitDataAsync(message)) diff --git a/src/TouchSocket.Rpc/Attribute/RpcAttribute.cs b/src/TouchSocket.Rpc/Attribute/RpcAttribute.cs index 4837964ed..2b3748867 100644 --- a/src/TouchSocket.Rpc/Attribute/RpcAttribute.cs +++ b/src/TouchSocket.Rpc/Attribute/RpcAttribute.cs @@ -44,8 +44,8 @@ public abstract class RpcAttribute : Attribute /// 生成代码 /// public CodeGeneratorFlag GeneratorFlag { get; set; } = - CodeGeneratorFlag.InstanceSync | CodeGeneratorFlag.InstanceAsync | CodeGeneratorFlag.ExtensionSync | CodeGeneratorFlag.ExtensionAsync - | CodeGeneratorFlag.InterfaceSync | CodeGeneratorFlag.InterfaceAsync; + CodeGeneratorFlag.InstanceAsync | CodeGeneratorFlag.ExtensionAsync + | CodeGeneratorFlag.InterfaceAsync; /// /// 生成泛型方法的约束 @@ -85,11 +85,7 @@ public abstract class RpcAttribute : Attribute public virtual string GetDescription(RpcMethod rpcMethod) { var description = rpcMethod.GetDescription(); - if (description.HasValue()) - { - return this.ReplacePatterns(description); - } - return "无注释信息"; + return description.HasValue() ? this.ReplacePatterns(description) : "无注释信息"; } /// @@ -105,56 +101,56 @@ public abstract class RpcAttribute : Attribute var parametersStr = this.GetParameters(rpcMethod, out var parameters); var InterfaceTypes = this.GetGenericConstraintTypes(); - if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.ExtensionSync)) - { - codeString.AppendLine("///"); - codeString.AppendLine($"///{description}"); - codeString.AppendLine("///"); - foreach (var item in this.Exceptions) - { - codeString.AppendLine($"/// {item.Value}"); - } + //if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.ExtensionSync)) + //{ + // codeString.AppendLine("///"); + // codeString.AppendLine($"///{description}"); + // codeString.AppendLine("///"); + // foreach (var item in this.Exceptions) + // { + // codeString.AppendLine($"/// {item.Value}"); + // } - codeString.AppendLine("[AsyncToSyncWarning]"); - codeString.Append("public static "); - codeString.Append(this.GetReturn(rpcMethod, false)); - codeString.Append(' '); - codeString.Append(this.GetMethodName(rpcMethod, false)); - codeString.Append("(");//方法参数 + // codeString.AppendLine("[AsyncToSyncWarning]"); + // codeString.Append("public static "); + // codeString.Append(this.GetReturn(rpcMethod, false)); + // codeString.Append(' '); + // codeString.Append(this.GetMethodName(rpcMethod, false)); + // codeString.Append("(");//方法参数 - codeString.Append($"this TClient client"); + // codeString.Append($"this TClient client"); - codeString.Append(','); - for (var i = 0; i < parametersStr.Count; i++) - { - if (i > 0) - { - codeString.Append(','); - } + // codeString.Append(','); + // for (var i = 0; i < parametersStr.Count; i++) + // { + // if (i > 0) + // { + // codeString.Append(','); + // } - codeString.Append(parametersStr[i]); - } - if (parametersStr.Count > 0) - { - codeString.Append(','); - } - codeString.Append(this.GetInvokeOption()); - codeString.AppendLine(") where TClient:"); + // codeString.Append(parametersStr[i]); + // } + // if (parametersStr.Count > 0) + // { + // codeString.Append(','); + // } + // codeString.Append(this.GetInvokeOption()); + // codeString.AppendLine(") where TClient:"); - for (var i = 0; i < InterfaceTypes.Length; i++) - { - if (i > 0) - { - codeString.Append(','); - } + // for (var i = 0; i < InterfaceTypes.Length; i++) + // { + // if (i > 0) + // { + // codeString.Append(','); + // } - codeString.Append(InterfaceTypes[i].FullName); - } + // codeString.Append(InterfaceTypes[i].FullName); + // } - codeString.AppendLine("{");//方法开始 - codeString.AppendLine(this.GetExtensionInstanceMethod(rpcMethod, parametersStr, parameters, false)); - codeString.AppendLine("}"); - } + // codeString.AppendLine("{");//方法开始 + // codeString.AppendLine(this.GetExtensionInstanceMethod(rpcMethod, parametersStr, parameters, false)); + // codeString.AppendLine("}"); + //} //以下生成异步 if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.ExtensionAsync)) @@ -232,43 +228,43 @@ public abstract class RpcAttribute : Attribute var description = this.GetDescription(rpcMethod); var parametersStr = this.GetParameters(rpcMethod, out var parameters); - if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.InstanceSync)) - { - codeString.AppendLine("///"); - codeString.AppendLine($"///{description}"); - codeString.AppendLine("///"); - foreach (var item in this.Exceptions) - { - codeString.AppendLine($"/// {item.Value}"); - } - codeString.AppendLine("[AsyncToSyncWarning]"); - codeString.Append("public "); - codeString.Append(this.GetReturn(rpcMethod, false)); - codeString.Append(' '); - codeString.Append(this.GetMethodName(rpcMethod, false)); - codeString.Append('(');//方法参数 + //if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.InstanceSync)) + //{ + // codeString.AppendLine("///"); + // codeString.AppendLine($"///{description}"); + // codeString.AppendLine("///"); + // foreach (var item in this.Exceptions) + // { + // codeString.AppendLine($"/// {item.Value}"); + // } + // codeString.AppendLine("[AsyncToSyncWarning]"); + // codeString.Append("public "); + // codeString.Append(this.GetReturn(rpcMethod, false)); + // codeString.Append(' '); + // codeString.Append(this.GetMethodName(rpcMethod, false)); + // codeString.Append('(');//方法参数 - for (var i = 0; i < parametersStr.Count; i++) - { - if (i > 0) - { - codeString.Append(','); - } - codeString.Append(parametersStr[i]); - } - if (parametersStr.Count > 0) - { - codeString.Append(','); - } - codeString.Append(this.GetInvokeOption()); - codeString.AppendLine(")"); + // for (var i = 0; i < parametersStr.Count; i++) + // { + // if (i > 0) + // { + // codeString.Append(','); + // } + // codeString.Append(parametersStr[i]); + // } + // if (parametersStr.Count > 0) + // { + // codeString.Append(','); + // } + // codeString.Append(this.GetInvokeOption()); + // codeString.AppendLine(")"); - codeString.AppendLine("{");//方法开始 + // codeString.AppendLine("{");//方法开始 - codeString.AppendLine(this.GetInstanceMethod(rpcMethod, parametersStr, parameters, false)); + // codeString.AppendLine(this.GetInstanceMethod(rpcMethod, parametersStr, parameters, false)); - codeString.AppendLine("}"); - } + // codeString.AppendLine("}"); + //} //以下生成异步 if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.InstanceAsync)) @@ -324,36 +320,36 @@ public abstract class RpcAttribute : Attribute var codeString = new StringBuilder(); var description = this.GetDescription(rpcMethod); var parameters = this.GetParameters(rpcMethod, out _); - if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.InterfaceSync)) - { - codeString.AppendLine("///"); - codeString.AppendLine($"///{description}"); - codeString.AppendLine("///"); - foreach (var item in this.Exceptions) - { - codeString.AppendLine($"/// {item.Value}"); - } + //if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.InterfaceSync)) + //{ + // codeString.AppendLine("///"); + // codeString.AppendLine($"///{description}"); + // codeString.AppendLine("///"); + // foreach (var item in this.Exceptions) + // { + // codeString.AppendLine($"/// {item.Value}"); + // } - codeString.AppendLine("[AsyncToSyncWarning]"); - codeString.Append(this.GetReturn(rpcMethod, false)); - codeString.Append(' '); - codeString.Append(this.GetMethodName(rpcMethod, false)); - codeString.Append('(');//方法参数 - for (var i = 0; i < parameters.Count; i++) - { - if (i > 0) - { - codeString.Append(','); - } - codeString.Append(parameters[i]); - } - if (parameters.Count > 0) - { - codeString.Append(','); - } - codeString.Append(this.GetInvokeOption()); - codeString.AppendLine(");"); - } + // codeString.AppendLine("[AsyncToSyncWarning]"); + // codeString.Append(this.GetReturn(rpcMethod, false)); + // codeString.Append(' '); + // codeString.Append(this.GetMethodName(rpcMethod, false)); + // codeString.Append('(');//方法参数 + // for (var i = 0; i < parameters.Count; i++) + // { + // if (i > 0) + // { + // codeString.Append(','); + // } + // codeString.Append(parameters[i]); + // } + // if (parameters.Count > 0) + // { + // codeString.Append(','); + // } + // codeString.Append(this.GetInvokeOption()); + // codeString.AppendLine(");"); + //} if (this.GeneratorFlag.HasFlag(CodeGeneratorFlag.InterfaceAsync)) { @@ -396,14 +392,9 @@ public abstract class RpcAttribute : Attribute /// public virtual string GetInvokeKey(RpcMethod rpcMethod) { - if (this.MethodInvoke) - { - return this.GetMethodName(rpcMethod, false); - } - else - { - return !this.InvokeKey.IsNullOrEmpty() ? this.InvokeKey : $"{rpcMethod.ServerFromType.FullName}.{rpcMethod.Name}".ToLower(); - } + return this.MethodInvoke + ? this.GetMethodName(rpcMethod, false) + : !this.InvokeKey.IsNullOrEmpty() ? this.InvokeKey : $"{rpcMethod.ServerFromType.FullName}.{rpcMethod.Name}".ToLower(); } /// @@ -424,32 +415,15 @@ public abstract class RpcAttribute : Attribute public virtual string GetMethodName(RpcMethod rpcMethod, bool isAsync) { var name = this.MethodName; - if (name.HasValue()) - { - name = this.ReplacePatterns(name).Format(rpcMethod.Name); - } - else - { - name = rpcMethod.Name; - } + name = name.HasValue() ? this.ReplacePatterns(name).Format(rpcMethod.Name) : rpcMethod.Name; if (isAsync) { - if (name.EndsWith("Async")) - { - return name; - } - - return $"{name}Async"; + return name.EndsWith("Async") ? name : $"{name}Async"; } else { - if (name.EndsWith("Async")) - { - return name.RemoveLastChars(5); - } - - return name; + return name.EndsWith("Async") ? name.RemoveLastChars(5) : name; } } diff --git a/src/TouchSocket.Rpc/Code/CodeGenerator.cs b/src/TouchSocket.Rpc/Code/CodeGenerator.cs index 226bb6468..6087b17a1 100644 --- a/src/TouchSocket.Rpc/Code/CodeGenerator.cs +++ b/src/TouchSocket.Rpc/Code/CodeGenerator.cs @@ -341,15 +341,15 @@ public static class CodeGenerator rpcAttribute.SetClassCodeGenerator(classCodeGenerator); if (first) { - if (rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.InterfaceAsync) || rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.InterfaceSync)) + if (rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.InterfaceAsync)) { serverCellCode.IncludeInterface = true; } - if (rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.InstanceAsync) || rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.InstanceSync)) + if (rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.InstanceAsync)) { serverCellCode.IncludeInstance = true; } - if (rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.ExtensionAsync) || rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.ExtensionSync)) + if (rpcAttribute.GeneratorFlag.HasFlag(CodeGeneratorFlag.ExtensionAsync)) { serverCellCode.IncludeExtension = true; } diff --git a/src/TouchSocket.Rpc/Enum/CodeGeneratorFlag.cs b/src/TouchSocket.Rpc/Enum/CodeGeneratorFlag.cs index e04cb64bc..6d14fdd5a 100644 --- a/src/TouchSocket.Rpc/Enum/CodeGeneratorFlag.cs +++ b/src/TouchSocket.Rpc/Enum/CodeGeneratorFlag.cs @@ -21,6 +21,7 @@ public enum CodeGeneratorFlag /// /// 生成扩展同步代码 /// + [Obsolete("此配置已被弃用,目前已经不再支持同步代码生成", true)] ExtensionSync = 1, /// @@ -31,6 +32,7 @@ public enum CodeGeneratorFlag /// /// 生成实例类同步代码(源代码生成无效) /// + [Obsolete("此配置已被弃用,目前已经不再支持同步代码生成", true)] InstanceSync = 4, /// @@ -41,6 +43,7 @@ public enum CodeGeneratorFlag /// /// 生成接口同步代码 /// + [Obsolete("此配置已被弃用,目前已经不再支持同步代码生成", true)] InterfaceSync = 16, /// diff --git a/src/TouchSocket/Options/TransportOption.cs b/src/TouchSocket/Options/TransportOption.cs index b9dc08fa7..9d99ca2d0 100644 --- a/src/TouchSocket/Options/TransportOption.cs +++ b/src/TouchSocket/Options/TransportOption.cs @@ -24,10 +24,12 @@ public class TransportOption /// public TransportOption() { - this.ReceivePipeOptions = CreateDefaultPipeOptions(); - this.SendPipeOptions = CreateDefaultPipeOptions(); + this.ReceivePipeOptions = CreateDefaultReadPipeOptions(); + this.SendPipeOptions = CreateDefaultWritePipeOptions(); } + public bool BufferOnDemand { get; set; } = true; + /// /// 获取或设置最大缓冲区大小(字节)。 /// @@ -48,25 +50,8 @@ public class TransportOption /// public PipeOptions SendPipeOptions { get; set; } - public bool BufferOnDemand { get; set; } = true; - /// - /// 创建默认的 。 - /// - public static PipeOptions CreateDefaultPipeOptions() - { - return new PipeOptions( - pool: null, - readerScheduler: null, - writerScheduler: null, - pauseWriterThreshold: -1, - resumeWriterThreshold: -1, - minimumSegmentSize: -1, - useSynchronizationContext: true); - } - - /// - /// 创建注重调度的 ,适合需要主线程调度的场景。 + /// 创建注重调度的 。 /// public static PipeOptions CreateSchedulerOptimizedPipeOptions() { @@ -74,9 +59,33 @@ public class TransportOption pool: null, readerScheduler: PipeScheduler.Inline, writerScheduler: PipeScheduler.Inline, - pauseWriterThreshold: -1, - resumeWriterThreshold: -1, + pauseWriterThreshold: 1024 * 64, + resumeWriterThreshold: 1024 * 32, minimumSegmentSize: -1, useSynchronizationContext: false); } + + private static PipeOptions CreateDefaultReadPipeOptions() + { + return new PipeOptions( + pool: null, + readerScheduler: PipeScheduler.ThreadPool, + writerScheduler: PipeScheduler.ThreadPool, + pauseWriterThreshold: 1024 * 1024, + resumeWriterThreshold: 1024 * 512, + minimumSegmentSize: -1, + useSynchronizationContext: true); + } + + private static PipeOptions CreateDefaultWritePipeOptions() + { + return new PipeOptions( + pool: null, + readerScheduler: PipeScheduler.ThreadPool, + writerScheduler: PipeScheduler.ThreadPool, + pauseWriterThreshold: 64 * 1024, + resumeWriterThreshold: 32 * 1024, + minimumSegmentSize: -1, + useSynchronizationContext: true); + } } \ No newline at end of file