DBTaskQueue.cs 1.1 KB
Newer Older
T
tanghai 已提交
1 2 3 4 5
using System;
using System.Threading.Tasks;

namespace Model
{
T
tanghai 已提交
6 7
	[ObjectEvent]
	public class DBTaskQueueEvent : ObjectEvent<DBTaskQueue>, IAwake, IStart
T
tanghai 已提交
8
	{
T
tanghai 已提交
9 10 11 12 13
		public void Awake()
		{
			DBTaskQueue self = this.Get();
			self.queue.Clear();
		}
T
tanghai 已提交
14 15 16

		public async void Start()
		{
T
tanghai 已提交
17 18
			DBTaskQueue self = this.Get();

T
tanghai 已提交
19 20
			while (true)
			{
T
tanghai 已提交
21
				if (self.Id == 0)
T
tanghai 已提交
22 23 24
				{
					return;
				}
T
tanghai 已提交
25 26

				DBTask task = await self.Get();
T
tanghai 已提交
27 28 29 30

				try
				{
					await task.Run();
T
tanghai 已提交
31 32

					task.Dispose();
T
tanghai 已提交
33 34 35 36 37 38 39
				}
				catch (Exception e)
				{
					Log.Error(e.ToString());
				}
			}
		}
T
tanghai 已提交
40 41 42 43 44 45 46 47
	}

	public sealed class DBTaskQueue : Disposer
	{
		public EQueue<DBTask> queue = new EQueue<DBTask>();

		public TaskCompletionSource<DBTask> tcs;

T
tanghai 已提交
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
		public void Add(DBTask task)
		{
			if (this.tcs != null)
			{
				var t = this.tcs;
				this.tcs = null;
				t.SetResult(task);
				return;
			}
			
			this.queue.Enqueue(task);
		}

		public Task<DBTask> Get()
		{
			if (this.queue.Count > 0)
			{
				DBTask task = this.queue.Dequeue();
T
tanghai 已提交
66
				return Task.FromResult(task);
T
tanghai 已提交
67
			}
T
tanghai 已提交
68 69 70

			TaskCompletionSource<DBTask> t = new TaskCompletionSource<DBTask>();
			this.tcs = t;
T
tanghai 已提交
71 72 73 74
			return t.Task;
		}
	}
}