CSoft.Utils 11.0.1

dotnet add package CSoft.Utils --version 11.0.1
                    
NuGet\Install-Package CSoft.Utils -Version 11.0.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="CSoft.Utils" Version="11.0.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="CSoft.Utils" Version="11.0.1" />
                    
Directory.Packages.props
<PackageReference Include="CSoft.Utils" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add CSoft.Utils --version 11.0.1
                    
#r "nuget: CSoft.Utils, 11.0.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package CSoft.Utils@11.0.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=CSoft.Utils&version=11.0.1
                    
Install as a Cake Addin
#tool nuget:?package=CSoft.Utils&version=11.0.1
                    
Install as a Cake Tool

CSoft.Utils

CSoft.Utils 是一个 .NET 工具库,提供异步队列、字节和字符串转换、CRC 校验、定时器、失败重试、插件发现及信号量程转换。

安装

在应用项目目录执行以下命令。

dotnet add package CSoft.Utils --version 11.0.1

库提供 netstandard2.0、net8.0、net9.0、net10.0 和 net11.0 目标程序集。PushQueue<T> 的批处理和刷新从 11.0.1 开始提供。

从本地源码开发时,也可以添加项目引用。

dotnet add reference ../Utils/Utils/Utils.csproj

上面的路径假设应用项目目录与本仓库目录同级。

工具索引

类型 用途
PushQueue<T> 后台顺序消费,支持限制待处理条数、批量回调和刷新。
StringByteUtils 十六进制文本转换、合并和比较字节数组、按指定字节序读写整数和浮点数。
CRC 计算 Modbus CRC-16、GBcrc16、HBcrc16 和 CRC-16/CCITT-FALSE。
RemainBytes 缓存分段收到的字节,通过偏移和长度读取有效数据,按需移除已处理的前缀。
StringUtils 提取文本中的数值、将对象属性转为 URI 查询参数、解析主机名。
SignalToDigitalProcessor 在线性信号量程和数字量量程之间双向转换,超出范围时取对应端点。
ProcessUtils 通过 ReTry 执行带取消检查的异步重试。
Utils.Timer.Timer 按本地时间的整分钟边界触发,支持延后通知。
PluginHelper 扫描应用目录下 Plugins/<目录> 中的 DLL,按接口名或完整类型名查找公开类型,也可通过构造参数创建实例。
AES · MD5 AES 字符串加解密,以及用于兼容既有格式的 Base64 或小写十六进制 MD5 摘要。

PushQueue

逐条消费

默认构造函数启用逐条回调。单个后台工作任务按入队顺序调用 OnPushData。有多个生产者时传入 singleWriter: false。

using Utils;

var queue = new PushQueue<int> { MaxCacheCount = 100 };
var processed = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously);
queue.OnPushData += item =>
{
    processed.TrySetResult(item);
    return Task.CompletedTask;
};

await queue.StartAsync();
try
{
    await queue.PutInDataAsync(42);
    Console.WriteLine(await processed.Task); // 42
}
finally
{
    await queue.StopAsync();
}
  • PutInDataAsync 完成表示数据已入队。示例通过回调中的 TaskCompletionSource 确认该项已处理。
  • MaxCacheCount 大于 0 时限制尚未取出的数据条数。到达上限后,await PutInDataAsync 会抛出 MaxCacheCountOutOfRangeException。小于或等于 0 表示容量无限制。
  • 队列传递原始引用。入队的是可变对象或池化缓冲区时,应保证它在回调处理完成前仍可使用。
  • 默认模式直接调用 OnPushData。需要等待多项异步处理时,可以在同一个回调中依次 await。多个独立订阅者共用该委托时,队列等待的是最后一个订阅者返回的任务。

批处理和刷新

构造时设置 enableBatchAndFlush: true,即可订阅 OnPushBatch 并调用 FlushAsync。

using Utils;

var queue = new PushQueue<int>(singleWriter: true, enableBatchAndFlush: true)
{
    MaxCacheCount = 100,
    MaxBatchCount = 16
};

queue.OnPushBatch += batch =>
{
    Console.WriteLine(string.Join(", ", batch));
    return Task.CompletedTask;
};

await queue.StartAsync();
try
{
    for (var item = 1; item <= 3; item++)
        await queue.PutInDataAsync(item);

    await queue.FlushAsync();
}
finally
{
    await queue.StopAsync();
}
  • OnPushBatch 接收当时已经可读取的数据,每批最多 MaxBatchCount 条,默认为 1。队列会在刷新边界处分批。同时订阅两个事件时,先等本批回调完成,再逐条调用 OnPushData。
  • FlushAsync 在队列运行期间调用。它等登记前入队的数据完成回调,并报告自上次完成刷新以来遇到的首个回调异常。队列继续消费后续数据。取消令牌在登记刷新请求前生效。
  • 需要在退出前处理积压时,先停止生产数据,再依次调用 FlushAsync 和 StopAsync。

停止和清空

StopAsync 等当前处理结束,保留尚未取出的数据。等待停止完成后再次调用 StartAsync,可以继续处理这些数据。Clear 丢弃尚未取出的数据,已开始的回调继续执行。开启增强模式时,两种操作都会取消尚未完成的刷新请求。

在回调外部等待 FlushAsync 和 StopAsync,因为它们需要等回调结束。

字节序和 CRC

StringToBytes 接受紧凑或以空白分隔的十六进制字符,也接受 0x 前缀。整数读写和 .NET 8 至 11 目标的浮点读写都用 isHighByteBefore 指定字节序。false 表示低字节在前,true 表示高字节在前。netstandard2.0 的浮点读写以 BitConverter 的本机字节序为基准,传 true 时反转字节。

using Utils;

var payload = StringByteUtils.StringToBytes("01 03 00 00 00 02");
var frame = CRC.Crc16(payload);
Console.WriteLine(StringByteUtils.BytesToString(frame)); // 01 03 00 00 00 02 C4 0B

var registerCount = StringByteUtils.ToUInt16(frame, startIndex: 4, isHighByteBefore: true);
Console.WriteLine(registerCount); // 2

CRC.Crc16(data, len) 返回前 len 字节的两字节 CRC,低字节在前。CRC.Crc16(data) 返回带 CRC 的新帧。

处理分段输入时,RemainBytes.Bytes 是底层数组,有效数据范围由 StartIndex 和 Count 指定。先用 Append 追加,再用 RemoveHeader 移除已处理的字节。追加可能扩容,继续读取前应重新取得数组和偏移。

异步重试

reTryCount 表示首次失败后允许再尝试的次数。下面的操作最多执行 3 次。

using Utils;

var attempts = 0;
Func<Task<int>> readValue = () =>
{
    if (++attempts == 1)
        throw new InvalidOperationException("暂时读取失败");

    return Task.FromResult(42);
};

Console.WriteLine(await readValue.ReTry(reTryCount: 2)); // 42

全部尝试失败时抛出 MultipleRetryFailureException,InnerException 保留最后一次失败的原因。取消令牌在每次尝试前检查,执行中的操作可通过委托传入同一个令牌。

定时和量程转换

  • new Utils.Timer.Timer(AverageTime.FiveMinutes, offset: 200) 按本地时间对齐每五分钟的边界,并延迟约 200 毫秒调用 OnTime。事件参数是计划触发的整分钟时间。用 StartAsync 启动,用 StopAsync 停止。
  • new SignalToDigitalProcessor(4m, 20m, 0m, 100m) 将 4–20 mA 映射到 0–100。此时 InputDataProcess(12m) 得到 50,OutputDataProcess(50m) 得到 12。

AES 字符串加解密

AES 默认使用 CBC 和 PKCS7,密钥长度可以是 16、24 或 32 字节。使用 CBC 时提供 16 字节 IV。Encrypt 将 UTF-8 明文加密并返回 Base64,Decrypt 使用对应的密钥、模式、填充和 IV 解密。

using System.Security.Cryptography;

using var keyMaterial = Aes.Create();
keyMaterial.GenerateKey();
keyMaterial.GenerateIV();

using var cipher = new Utils.AES(keyMaterial.Key, iv: keyMaterial.IV);
var encrypted = cipher.Encrypt("hello");
Console.WriteLine(cipher.Decrypt(encrypted)); // hello

构建和测试

在仓库根目录使用 .NET 11 SDK 构建。运行全部测试需要 .NET 10 和 .NET 11 运行时。

dotnet build Utils.sln -c Release
dotnet test Utils.sln -c Release
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed.  net11.0 is compatible. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (6)

Showing the top 5 NuGet packages that depend on CSoft.Utils:

Package Downloads
CSoft.Communication

通信物理口封装

CSoft.Parser

数据分帧解析器

CSoft.Crow

数据收发队列

CSoft.CommTask

通信队列核心层(Crow/Pigeon/Sparrow)

CSoft.PipeLine

流水线控制

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
11.0.1 1,322 11/11/2026
11.0.0 375 11/11/2026
10.0.6 3,538 5/25/2026
10.0.5 2,819 5/15/2026
10.0.4 6,730 3/18/2026
10.0.3 1,090 1/14/2026
10.0.2 3,250 12/10/2025
10.0.1 688 12/8/2025
10.0.0 1,299 11/12/2025
9.2.0 659 10/20/2025
9.1.9 293 10/20/2025
9.1.8 2,896 8/6/2025
9.1.7 3,385 7/22/2025
9.1.6 3,410 3/20/2025
9.1.5 1,245 3/18/2025
9.1.4 1,614 2/14/2025
9.1.3 287 2/14/2025 9.1.3 is deprecated because it is no longer maintained.
9.1.2 321 2/13/2025 9.1.2 is deprecated because it has critical bugs.
9.1.1 1,707 1/23/2025
9.1.0 293 1/23/2025 9.1.0 is deprecated because it has critical bugs.
Loading failed

PushQueue 支持按需启用批量消费和 FlushAsync,完善容量限制及停止后的重启行为。附带中文使用文档。