当然可以!以下是一道**专家级别**的 **C# 程序员逻辑面试题**,它结合了对 **委托、事件、异步编程、闭包、线程安全和设计模式** 的理解,适合用于考察高级开发人员的综合能力。 --- ### 🧠 面试题:实现一个线程安全的事件总线(Event Bus)并支持异步订阅 #### 📌 题目描述: 请你实现一个轻量级的**线程安全事件总线(Event Bus)**,满足以下要求: 1. 支持订阅者注册(Subscribe)和注销(Unsubscribe)。 2. 事件处理方法可以是同步或异步(即支持 `Action` 和 `Func`)。 3. 支持发布事件(Publish),所有订阅该事件的处理方法都会被调用。 4. 支持弱引用订阅,防止内存泄漏(选做加分项)。 5. 在多线程环境下是安全的(即并发调用 Subscribe/Publish 不会出现异常或状态不一致)。 6. 实现一个简单的示例,演示其使用方式。 --- ### 📝 示例接口设计(可参考): ```csharp public interface IEventBus { void Subscribe(Action handler) where T : class; void Subscribe(Func handler) where T : class; void Unsubscribe(Action handler) where T : class; void Unsubscribe(Func handler) where T : class; void Publish(T @event) where T : class; } ``` --- ### 💡 考察点解析: | 技术点 | 考察内容 | |--------|----------| | 委托与泛型 | 使用 `Action` 和 `Func` 作为事件处理器 | | 多线程安全 | 使用 `ConcurrentDictionary`、锁等机制保证线程安全 | | 异步编程 | 正确地在 Publish 中调用 `await` 所有异步处理函数 | | 弱引用(加分项) | 使用 `WeakReference` 避免内存泄漏 | | 闭包与捕获变量 | 避免因闭包导致的意外行为 | | 设计模式 | 观察者模式的实现能力 | | 性能优化 | 如何高效存储和调用多个事件处理器 | --- ### ✅ 参考答案(简化实现): ```csharp public class EventBus : IEventBus { private readonly ConcurrentDictionary _handlers = new ConcurrentDictionary(); private readonly object _lock = new object(); public void Subscribe(Action handler) where T : class { AddHandler(handler); } public void Subscribe(Func handler) where T : class { AddHandler(handler); } private void AddHandler(object handler) where T : class { _handlers.AddOrUpdate( typeof(T), new List { handler }, (t, list) => { lock (_lock) { var handlers = (List)list; handlers.Add(handler); return handlers; } }); } public void Unsubscribe(Action handler) where T : class { RemoveHandler(handler); } public void Unsubscribe(Func handler) where T : class { RemoveHandler(handler); } private void RemoveHandler(object handler) where T : class { var type = typeof(T); if (_handlers.TryGetValue(type, out var list)) { lock (_lock) { var handlers = (List)list; handlers.Remove(handler); if (!handlers.Any()) { _handlers.TryRemove(type, out _); } } } } public void Publish(T @event) where T : class { if (_handlers.TryGetValue(typeof(T), out var handlersObj)) { var handlers = ((List)handlersObj).ToList(); foreach (var handler in handlers) { if (handler is Action syncHandler) { syncHandler(@event); } else if (handler is Func asyncHandler) { // 在异步上下文中应 await,这里简化处理 asyncHandler(@event); } } } } } ``` --- ### 🧪 使用示例: ```csharp public class MyEvent { public string Message { get; set; } } class Program { static async Task Main(string[] args) { var eventBus = new EventBus(); eventBus.Subscribe(e => Console.WriteLine($"Sync handler: {e.Message}")); eventBus.Subscribe(async e => { await Task.Delay(100); Console.WriteLine($"Async handler: {e.Message}"); }); eventBus.Publish(new MyEvent { Message = "Hello World!" }); await Task.Delay(500); // 等待异步事件完成 } } ``` --- ### 📌 总结: 这道题不仅考察了语言基础,还涉及了**并发编程、泛型、委托、事件模型和设计思想**,非常适合用于评估高级 C# 工程师的综合能力。 如果你需要,我也可以为你提供一个带弱引用实现的完整版本。需要吗?
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog