C# await async 异步任务

该博客介绍了如何通过创建一个自定义的AsyncTask类来简化Unity中Addressable异步加载资源的过程,使代码更易读。AsyncTask包含了一个AwaiterStatus枚举来表示任务状态,并实现了获取等待器、检查是否完成、设置结果和获取结果的方法。在使用示例中,展示了如何加载并实例化一个资源,然后在完成时调用回调函数。
摘要由CSDN通过智能技术生成

Addressable异步加载资源写起来有些地方不太好控制代码结构。所以我简单做了一个AsyncTask,这样代码写起来简单易懂。

[AsyncMethodBuilder(typeof(AsyncSTaskMethodBuilder))]//指定Builder类,async修饰所必须
    public class AsyncTask<T> where T : UnityEngine.Object
    {
        public enum AwaiterStatus
        {
            Pending = 0,
            Succeeded = 1,
            Faulted = 2,
            Canceled = 3
        }
        private AwaiterStatus status { get; set; }

        private Awaiter<T> awaiter;

        T Resualt;

        public Awaiter<T> GetAwaiter()
        {
            status = AwaiterStatus.Pending;
            awaiter = new Awaiter<T>(this);
            return awaiter;
        }

        public bool IsComplete()
        {
            Debug.Log($"AsyncTask -> IsCompleted????{status} {status != AwaiterStatus.Pending}");
            return status != AwaiterStatus.Pending; 
        }

        public void OnComplete(T value)
        {
            Debug.Log($"AsyncTask -> OnComplete");
            status = AwaiterStatus.Succeeded;
            Resualt = value;
            awaiter.TryInvokeContinuation();
        }

        public T GetResualt()
        {
            return Resualt;
        }
    }

    public class Awaiter<T> : ICriticalNotifyCompletion where T : UnityEngine.Object
    {
        
        Action continuation;

        
        private AsyncTask<T> asyncTask;
        internal Awaiter(AsyncTask<T> asyncTask)
        {
            this.asyncTask = asyncTask;
        }

        public bool IsCompleted { get { return this.asyncTask.IsComplete(); } }


        public void OnCompleted(Action continuation)
        {
            Debug.Log($"Awaiter -> OnCompleted");
            if (IsCompleted)
            {
                continuation?.Invoke();
            }
        }

        public void UnsafeOnCompleted(Action continuation)
        {
            this.continuation = continuation;
            Debug.Log($"Awaiter -> UnsafeOnCompleted");
            if(IsCompleted)
            {
                continuation?.Invoke();
            }
        }

        public void GetResult()
        {
            Debug.Log($"Awaiter -> GetResult");
        }

        public void TryInvokeContinuation()
        {
            this.continuation?.Invoke();
            this.continuation = null;
        }

        
    }

 使用方式

public AsyncTask<T> LoadAssetInstance<T>(string asstesName, bool isRelease = false, Action<T> callBack = null) where T : UnityEngine.Object
        {
            AsyncTask<T> task = new AsyncTask<T>();
            AsyncOperationHandle handle = Addressables.LoadAssetAsync<T>(asstesName);
            handle.Completed += op => {

                if (op.Status != AsyncOperationStatus.Succeeded)
                {
                    Debug.LogError($"LoadAsset 加载资源出错{asstesName}");
                    return ;
                }

                if (op.Result == null)
                {
                    Debug.LogError($"LoadAsset 没有加载到资源{asstesName}");
                    return;
                }
                //Debug.LogFormat("LoadAssetTest Completed!");
                var go = GameObject.Instantiate(op.Result as T);
                task.OnComplete(go);
                callBack?.Invoke(go);
                if (isRelease)
                {
                    Addressables.Release(op);
                }
            };
            return task;
        }
Debug.Log("测试异步");
var go = AddressableManager.Instance.LoadAssetInstance<GameObject>("JadePanel_Main");
await go;
Debug.Log(go.GetResualt().name);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值