Tech.Core 2026.4.6

dotnet add package Tech.Core --version 2026.4.6
                    
NuGet\Install-Package Tech.Core -Version 2026.4.6
                    
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="Tech.Core" Version="2026.4.6" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Tech.Core" Version="2026.4.6" />
                    
Directory.Packages.props
<PackageReference Include="Tech.Core" />
                    
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 Tech.Core --version 2026.4.6
                    
#r "nuget: Tech.Core, 2026.4.6"
                    
#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 Tech.Core@2026.4.6
                    
#: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=Tech.Core&version=2026.4.6
                    
Install as a Cake Addin
#tool nuget:?package=Tech.Core&version=2026.4.6
                    
Install as a Cake Tool

Tech.Core API 文档

Tech.Core 是一个零外部依赖的 .NET 工具库,提供缓存、GUID 生成、内存管理、JSON 处理、并行计算等核心能力。

Caching

Tech.Caching 命名空间提供线程安全的泛型缓存,支持四种淘汰策略。

淘汰策略

策略 枚举值 说明
LRU CacheEvictionPolicy.LRU 最近最少使用,使用 SortedDictionary + 原子时间戳优化
LFU CacheEvictionPolicy.LFU 最不经常使用,惰性清理陈旧条目
FIFO CacheEvictionPolicy.FIFO 先进先出,基于 LinkedList
MRU CacheEvictionPolicy.MRU 最近最多使用,链表头部淘汰

ICache<TKey, TValue>

public interface ICache<TKey, TValue> : IDisposable where TKey : notnull
{
    int Capacity { get; }
    int Count { get; }
    CacheEvictionPolicy Policy { get; }
    bool TryGet(TKey key, out TValue? value);
    void Set(TKey key, TValue value);
    bool Remove(TKey key);
    void Clear();
}

CacheFactory

// 通用创建
var cache = CacheFactory.Create<string, object>(1000, CacheEvictionPolicy.LRU);

// 快捷方法
var lru  = CacheFactory.CreateLRU<string, object>(1000);
var lfu  = CacheFactory.CreateLFU<string, object>(1000);
var fifo = CacheFactory.CreateFIFO<string, object>(1000);
var mru  = CacheFactory.CreateMRU<string, object>(1000);

使用示例

using Tech.Caching;

var cache = CacheFactory.CreateLRU<int, string>(100);

cache.Set(1, "Hello");
cache.Set(2, "World");

if (cache.TryGet(1, out var value))
{
    Console.WriteLine(value); // Hello
}

cache.Remove(1);
Console.WriteLine(cache.Count); // 1

cache.Dispose();

Guids

Tech.Guids 命名空间提供数据库友好的顺序 GUID 生成器,避免随机 GUID 导致的索引碎片。

GuidType 枚举

说明 适用数据库
SequentialAsString 时间戳在前(字符串排序) MySQL、PostgreSQL
SequentialAsBinary 时间戳在前(二进制排序) Oracle
SequentialAtEnd 时间戳在后(默认) SQL Server
NonSequentialAsString 随机 GUID 通用

GuidGenerator

// 默认生成(SequentialAtEnd)
var guid = GuidGenerator.NewGuid();

// 指定类型
var guid = GuidGenerator.NewGuid(GuidType.SequentialAsString);

// 单例实例
var generator = GuidGenerator.Instance;
var guid = generator.Create();
var guid = generator.Create(GuidType.SequentialAtEnd);

SequentialGuid 快捷方法

var guid = SequentialGuid.NewGuid();              // 默认 SequentialAtEnd
var guid = SequentialGuid.NewGuidForSqlServer();   // SequentialAtEnd
var guid = SequentialGuid.NewGuidForMySql();       // SequentialAsString
var guid = SequentialGuid.NewGuidForPostgreSql();  // SequentialAsString
var guid = SequentialGuid.NewGuidForOracle();      // SequentialAsBinary

GuidGeneratorOptions

var options = new GuidGeneratorOptions
{
    DefaultGuidType = GuidType.SequentialAsString
};

Memory

Tech.Memory 命名空间提供智能内存数组,根据数组大小自动选择直连内存(小数组)或池化内存(大数组)策略。

IMemoryArray<T>

public interface IMemoryArray<T> : IMemoryOwner<T>, IEnumerable<T>
{
    ReadOnlyMemory<T> ReadOnlyMemory { get; }
    Span<T> Span { get; }
    ReadOnlySpan<T> ReadOnlySpan { get; }
    int Length { get; }
    bool IsDisposed { get; }
    T this[int index] { get; set; }
    IMemoryArray<T> Clone();
}

MemoryArray<T> 工厂方法

// 自动选择策略(默认阈值 1024 元素)
var array = MemoryArray<double>.Create(10000);

// 强制策略
var pooled  = MemoryArray<double>.CreatePooled(10000);  // ArrayPool
var direct  = MemoryArray<double>.CreateDirect(100);     // GC 管理
var wrapped = MemoryArray<double>.WrapDirect(existingArray); // 零拷贝包装

构造函数

// 指定长度和池化阈值
var array = new MemoryArray<byte>(10000, poolingThreshold: 512);

// 从已有数组创建
var array = new MemoryArray<int>(new[] { 1, 2, 3 });

并行处理扩展

var array = MemoryArray<double>.Create(100000);

// 并行遍历
array.ParallelForEach(item => Process(item));

// 并行分块处理
array.ParallelForEachBatched(
    (Span<double> batch) => ProcessBatch(batch),
    batchSize: 1000
);

Json

Tech.Json 命名空间封装 System.Text.Json,提供一致的默认配置和便捷 API。

默认配置

  • CamelCase 命名策略
  • 忽略 null 值
  • 忽略循环引用
  • 允许尾随逗号
  • 允许注释
  • DateTime 格式:yyyy-MM-dd HH:mm:ss
  • 枚举使用 CamelCase 字符串

JSON 静态类

using Tech.Json;

// 序列化
string json = JSON.Serialize(obj);
byte[] bytes = JSON.SerializeToUtf8Bytes(obj);

// 反序列化
var obj = JSON.Deserialize<MyClass>(json);
var obj = JSON.DeserializeFromUtf8Bytes<MyClass>(bytes);

// 异步
string json = await JSON.SerializeAsync(obj);
byte[] bytes = await JSON.SerializeToUtf8BytesAsync(obj);
var obj = await JSON.DeserializeAsync<MyClass>(json);

扩展方法

// 对象 → JSON
string json = myObj.ToJson();
byte[] bytes = myObj.ToJsonBytes();

// JSON → 对象
var obj = json.ToObject<MyClass>();
var obj = bytes.ToObjectFromBytes<MyClass>();

自定义 DateTime 转换器

var converter = new DateTimeJsonConverter("yyyy-MM-dd");
var options = new JsonSerializerOptions();
options.Converters.Add(converter);

Threading

Tech.Threading 命名空间提供异步锁、并行工具和读写锁扩展。

AsyncLock

using var asyncLock = new AsyncLock();

// 异步锁定
using (await asyncLock.LockAsync())
{
    // 临界区
}

// 同步锁定
using (asyncLock.Lock())
{
    // 临界区
}

// 带取消令牌
using (await asyncLock.LockAsync(cancellationToken))
{
    // 临界区
}

AsyncLock 执行扩展

var result = await asyncLock.DoAsync(() =>
{
    // 同步操作
    return 42;
});

var result = await asyncLock.DoAsync(async () =>
{
    // 异步操作
    await Task.Delay(100);
    return 42;
});

Parallel 工具类

using Tech.Threading;

// Parallel.For
Parallel.For(0, 100, i => Process(i));

// Parallel.ForEach
Parallel.ForEach(items, item => Process(item));

// 分块并行
Parallel.ForBatched(0, 1000, batchSize: 100, (from, to) => ProcessRange(from, to));
Parallel.ForEachBatched(items, batchSize: 100, batch => ProcessBatch(batch));

// 并行执行多个操作
Parallel.Invoke(action1, action2, action3);

// 并行映射
var results = Parallel.Map(items, item => Transform(item));

ParallelOptions

var options = new ParallelOptions
{
    MaxDegreeOfParallelism = 4,
    CancellationToken = ct,
    OnException = ex => LogError(ex)
};

Parallel.For(0, 100, i => Process(i), options);

ReaderWriterLockSlim 扩展

var rwLock = new ReaderWriterLockSlim();

// 读锁
var value = rwLock.Read(() => GetValue());
rwLock.Read(() => DoReadAction());

// 写锁
rwLock.Write(() => SetValue(42));
var result = rwLock.Write(() => ComputeAndReturn());

// 可升级读锁
var result = rwLock.UpgradeableRead(() =>
{
    var current = ReadValue();
    if (NeedsUpdate(current))
    {
        rwLock.Write(() => UpdateValue());
    }
    return ReadValue();
});

Collections

Tech.Collections 命名空间提供高性能集合扩展方法。

FastCount

类型检测优先级:T[] > IMemoryArray > ImmutableArray > ICollection > IReadOnlyCollection,避免 LINQ Count() 的枚举开销。

using Tech.Collections;

int count = source.FastCount();

FastChunk

分块处理,可选使用 ArrayPool 租用减少 GC 压力。

// 普通分块
foreach (var chunk in source.FastChunk(100))
{
    ProcessChunk(chunk.Span);
}

// 使用 ArrayPool(减少内存分配)
foreach (var chunk in source.FastChunk(100, usePool: true))
{
    ProcessChunk(chunk.Span);
}

Utils

GZip 压缩 / 解压

using Tech.Utils;

// 字符串压缩(Base64 编码)
string compressed = GZip.Compress("Hello World");
string original   = GZip.Decompress(compressed);

// 字节数组压缩
byte[] compressed = GZip.Compress(bytes);
byte[] original   = GZip.Decompress(compressed);

// 流压缩
byte[] compressed = GZip.Compress(stream);
byte[] original   = GZip.Decompress(stream);

// 流 → 字节数组
byte[] data = GZip.StreamToBytes(stream);
Product Compatible and additional computed target framework versions.
.NET 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net10.0

    • No dependencies.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on Tech.Core:

Package Downloads
Tech.Spatial

基于 .NET 10 的高性能基础设施组件库。

Tech.Numerics

基于 .NET 10 的高性能基础设施组件库。

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2026.4.6 119 4/6/2026
2026.4.4 111 4/4/2026
1.2.1 101 3/30/2026
1.2.0 100 3/30/2026
1.1.1 98 3/30/2026
1.1.0 103 3/29/2026
1.0.0 168 3/28/2026