AVObjectExtension

https://leancloud.cn/

using System.Collections.Generic;
using AVOSCloud;
using System.Threading.Tasks;
using System;

public static class AVObjectExtension
{
    private static Queue saveQueue = new Queue();
    private static Queue deleteQueue = new Queue();

    private static Dictionary> actions = new Dictionary>();

    public static void SaveAsync(this AVObject avObject, Action continuation)
    {
        lock (actions)
        {
            actions[avObject] = continuation;
        }

        lock (saveQueue)
        {
            if (saveQueue.Count == 0)
                Save(avObject);
            else
                saveQueue.Enqueue(avObject);
        }
    }

    private static void Save(AVObject avObject)
    {
        avObject.SaveAsync().ContinueWith(delegate (Task task)
        {
            lock (actions)
            {
                var continuation = actions[avObject];
                if(continuation != null)
                    continuation(task);
                actions.Remove(avObject);
            }

            lock (saveQueue)
            {
                if (saveQueue.Count != 0)
                    Save(saveQueue.Dequeue());
            }
        });
    }

    public static void DeleteAsync(this AVObject avObject, Action continuation)
    {
        lock (actions)
        {
            actions[avObject] = continuation;
        }

        lock (deleteQueue)
        {
            if (deleteQueue.Count == 0)
                Delete(avObject);
            else
                deleteQueue.Enqueue(avObject);
        }
    }

    private static void Delete(AVObject avObject)
    {
        avObject.DeleteAsync().ContinueWith(delegate (Task task)
        {
            lock (actions)
            {
                var continuation = actions[avObject];
                if (continuation != null)
                    continuation(task);
                actions.Remove(avObject);
            }

            lock (deleteQueue)
            {
                if (deleteQueue.Count != 0)
                    Delete(deleteQueue.Dequeue());
            }
        });
    }
}

你可能感兴趣的:(AVObjectExtension)