Make all AsyncOperations awaitable

Does this seem like a reasonable way to easily make all AsyncOperations awaitable?

        public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
        {
            var tcs = new TaskCompletionSource<AsyncOperation>();
            asyncOp.completed += operation => { tcs.SetResult(operation); };
            return ((Task)tcs.Task).GetAwaiter();
        }

this extension allows you to be able to do things like

            await webRequest.SendWebRequest();

I suppose the GC hit from it isn’t great, but does seem like a quick way of handling it.

I also guess if the async operation failed the await would never pass I think, maybe. Not sure. Maybe it would because a failure is still a completion, so complete probably still fires.

(maybe not the best forum for this, but AsyncOperations are done in addressable often, altho they are usually handles and the handles you can just do .Task)

1 Like

You can also use GitHub - Cysharp/UniTask: Provides an efficient allocation free async/await integration for Unity. it add alocation free UniTask class and add extension to await AsyncOperations