Skip to content

Instantly share code, notes, and snippets.

@AntonZhernosek
Last active August 13, 2023 04:45
Show Gist options
  • Save AntonZhernosek/2845b5e1aa738f52035c23d01f0a2316 to your computer and use it in GitHub Desktop.
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
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