Last active
August 13, 2023 04:45
-
-
Save AntonZhernosek/2845b5e1aa738f52035c23d01f0a2316 to your computer and use it in GitHub Desktop.
UnityWebRequest doesn't support async/await operations natively. With this small extension, it now has an awaiter and can be cancelled via a CancellationToken
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Runtime.CompilerServices; | |
using System.Threading; | |
using System.Threading.Tasks; | |
using UnityEngine.Networking; | |
namespace UnityUtilities.Networking.Extensions | |
{ | |
public static class UnityWebRequestExtension | |
{ | |
public static async Task<UnityWebRequest.Result> SendWebRequestAsync(this UnityWebRequest request, CancellationToken ct = default) | |
{ | |
if (ct.CanBeCanceled) | |
{ | |
ct.Register(request.Abort); | |
} | |
return await request.SendWebRequest(); | |
} | |
private static TaskAwaiter<UnityWebRequest.Result> GetAwaiter(this UnityWebRequestAsyncOperation webRequestOperation) | |
{ | |
TaskCompletionSource<UnityWebRequest.Result> tcs = new TaskCompletionSource<UnityWebRequest.Result>(); | |
webRequestOperation.completed += SetResult; | |
void SetResult(UnityEngine.AsyncOperation _) | |
{ | |
webRequestOperation.completed -= SetResult; | |
tcs.TrySetResult(webRequestOperation.webRequest.result); | |
} | |
if (webRequestOperation.isDone) | |
{ | |
webRequestOperation.completed -= SetResult; | |
tcs.TrySetResult(webRequestOperation.webRequest.result); | |
} | |
return tcs.Task.GetAwaiter(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment