DBQueryTask.cs 1.4 KB
Newer Older
T
tanghai 已提交
1 2 3 4 5 6 7
using System;
using System.Threading.Tasks;
using MongoDB.Driver;

namespace Model
{
	[ObjectEvent]
T
tanghai 已提交
8
	public class DBQueryTaskEvent : ObjectEvent<DBQueryTask>, IAwake<string, TaskCompletionSource<Disposer>>
T
tanghai 已提交
9
	{
T
tanghai 已提交
10
		public void Awake(string collectionName, TaskCompletionSource<Disposer> tcs)
T
tanghai 已提交
11 12 13 14 15 16 17 18 19 20 21
		{
			DBQueryTask self = this.Get();
			self.CollectionName = collectionName;
			self.Tcs = tcs;
		}
	}

	public sealed class DBQueryTask : DBTask
	{
		public string CollectionName { get; set; }

T
tanghai 已提交
22
		public TaskCompletionSource<Disposer> Tcs { get; set; }
T
tanghai 已提交
23 24 25 26 27 28 29 30 31 32

		public DBQueryTask(long id): base(id)
		{
		}

		public override async Task Run()
		{
			DBCacheComponent dbCacheComponent = Game.Scene.GetComponent<DBCacheComponent>();
			DBComponent dbComponent = Game.Scene.GetComponent<DBComponent>();
			// 执行查询前先看看cache中是否已经存在
T
tanghai 已提交
33 34
			Disposer disposer = dbCacheComponent.GetFromCache(this.CollectionName, this.Id);
			if (disposer != null)
T
tanghai 已提交
35
			{
T
tanghai 已提交
36
				this.Tcs.SetResult(disposer);
T
tanghai 已提交
37 38 39 40 41
				return;
			}
			try
			{
				// 执行查询数据库任务
T
tanghai 已提交
42 43
				disposer = await dbComponent.GetCollection(this.CollectionName).FindAsync((s) => s.Id == this.Id).Result.FirstOrDefaultAsync();
				if (disposer != null)
T
tanghai 已提交
44
				{
T
tanghai 已提交
45
					dbCacheComponent.AddToCache(disposer);
T
tanghai 已提交
46
				}
T
tanghai 已提交
47
				this.Tcs.SetResult(disposer);
T
tanghai 已提交
48 49 50 51 52 53 54 55
			}
			catch (Exception e)
			{
				this.Tcs.SetException(new Exception($"查询数据库异常! {CollectionName} {Id}", e));
			}
		}
	}
}