Young87

SmartCat's Blog

So happy to code my life!

游戏开发交流QQ群号60398951

当前位置:首页 >AI写作

c#题例-2025-06-11 19:52:20

好的!以下是一道专家级别的 C# 程序员逻辑面试题,涉及多线程、并发和内存管理等高级概念:

---

### 面试题:实现一个线程安全的缓存系统

**题目描述:**

你需要设计并实现一个线程安全的缓存系统 `ThreadSafeCache`,该系统支持以下功能:

1. **添加/更新键值对**:`void AddOrUpdate(TKey key, TValue value)`
- 如果键已存在,则更新其值;如果键不存在,则添加新的键值对。

2. **获取值**:`TValue Get(TKey key)`
- 根据键获取对应的值。如果键不存在,则抛出 `KeyNotFoundException`。

3. **删除键值对**:`void Remove(TKey key)`
- 删除指定键的键值对。如果键不存在,则什么都不做。

4. **清除所有数据**:`void Clear()`
- 清空缓存中的所有数据。

5. **过期机制**:
- 每个键值对可以有一个可选的过期时间(以秒为单位)。如果设置了过期时间,那么超过这个时间后,该键值对应自动从缓存中移除。

**要求:**

- 所有操作必须是线程安全的。
- 提供高效的并发访问机制(尽量减少锁的竞争)。
- 使用 C# 的 `ConcurrentDictionary` 或其他合适的并发集合来实现。
- 如果可能,使用异步编程模型来处理过期机制。

---

### 示例代码框架

以下是部分代码框架,你需要完成其中的关键逻辑:

```csharp
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;

public class ThreadSafeCache
{
private readonly ConcurrentDictionary> _cache = new ConcurrentDictionary>();

public void AddOrUpdate(TKey key, TValue value, int? expirationInSeconds = null)
{
// TODO: 实现 AddOrUpdate 方法
}

public TValue Get(TKey key)
{
// TODO: 实现 Get 方法
throw new KeyNotFoundException($"Key {key} not found in cache.");
}

public void Remove(TKey key)
{
// TODO: 实现 Remove 方法
}

public void Clear()
{
// TODO: 实现 Clear 方法
}

private class CacheEntry
{
public T Value { get; set; }
public DateTime? ExpirationTime { get; set; }

public CacheEntry(T value, DateTime? expirationTime)
{
Value = value;
ExpirationTime = expirationTime;
}
}

// 可选:实现过期清理逻辑
private async Task ExpireItemsAsync()
{
// TODO: 异步清理过期项
}
}
```

---

### 提示

1. **线程安全性**:考虑使用 `ConcurrentDictionary` 来避免手动加锁。
2. **过期机制**:可以通过后台任务定期检查并清理过期的键值对,或者在每次访问时动态检查是否过期。
3. **性能优化**:尽量减少锁的粒度,避免阻塞不必要的线程。

---

这道题目考察了候选人在多线程编程、并发集合、内存管理和异步编程等方面的能力,适合用于评估高级 C# 开发者的技能水平。

除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog

上一篇: c#题例-2025-06-12 02:38:49

下一篇: c#题例-2025-06-11 14:19:14

精华推荐