有什么不明白的地方,扫描右方二维码加我微信交流。
       

UnityWebRequest使用很方便,但是SendRequest方法不能await,只能在协程里调用,如何使得SendRequest可以await呢?

使一个对象可以await,这个对象必须有GetAwaiter方法,GetAwaiter方法里返回一个和异步操作完成状态的对象,这个对象必须实现3个方法:

  • IsCompleted
  • GetResult
  • OnCompleted

必须继承:INotifyCompletion

IsCompleted会在await时调用,如果返回false,则调用OnCompleted方法给continuation赋值,在构造这个对象时传入实现异步操作的对象,给异步操作对象的completed方法再添加一个OnRequestCompleted,实际上就是当异步操作完成时,从这里通知出去。通知出去后,会调用GetResult方法,此方法可以给await返回值,如果不写,则返回空值。

代码如下:

using System;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.Networking;

public class UnityWebRequestAwaiter : INotifyCompletion
{
    private UnityWebRequestAsyncOperation asyncOp;
    private Action continuation;

    public UnityWebRequestAwaiter(UnityWebRequestAsyncOperation asyncOp)
    {
        this.asyncOp = asyncOp;
        asyncOp.completed += OnRequestCompleted;
    }

    public bool IsCompleted { get { return asyncOp.isDone; } }

    public void GetResult() { }

    public void OnCompleted(Action continuation)
    {
        this.continuation = continuation;
    }

    private void OnRequestCompleted(AsyncOperation obj)
    {
        continuation();
    }
}

public static class ExtensionMethods
{
    public static UnityWebRequestAwaiter GetAwaiter(this UnityWebRequestAsyncOperation asyncOp)
    {
        return new UnityWebRequestAwaiter(asyncOp);
    }
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注