using System; using System.Collections.Generic; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Driver; namespace Model { [ObjectEvent] public class DbQueryBatchTaskSystem : ObjectSystem, IAwake, string, TaskCompletionSource>> { public void Awake(List idList, string collectionName, TaskCompletionSource> tcs) { DBQueryBatchTask self = this.Get(); self.IdList = idList; self.CollectionName = collectionName; self.Tcs = tcs; } } public sealed class DBQueryBatchTask : DBTask { public string CollectionName { get; set; } public List IdList { get; set; } public TaskCompletionSource> Tcs { get; set; } public override async Task Run() { DBCacheComponent dbCacheComponent = Game.Scene.GetComponent(); DBComponent dbComponent = Game.Scene.GetComponent(); List result = new List(); try { // 执行查询数据库任务 foreach (long id in IdList) { Disposer disposer = dbCacheComponent.GetFromCache(this.CollectionName, id); if (disposer == null) { disposer = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == id).Result.FirstOrDefaultAsync(); dbCacheComponent.AddToCache(disposer); } if (disposer == null) { continue; } result.Add(disposer); } this.Tcs.SetResult(result); } catch (Exception e) { this.Tcs.SetException(new Exception($"查询数据库异常! {this.CollectionName} {IdList.ListToString()}", e)); } } } }