Hi. I would like to use async/await patterns for http requests.
Do I need to use WebRequest and HttpWebRequest .net classes?
Youâre welcome to use whatever you want. Just be aware that:
-
async/await (to my knowledge) wonât work on the WebGL platform (someone correct me if this is wrong; I heard System.Threading is a non-starter on WebGL?)
-
everything you do to Unity objects must be done in the main thread, so if you want to roll your own HTTP stuff, either a) it cannot interoperate with Unity objects, or b) you must also write a marshaling layer to get it over into the main thread, usually by means of a job queue, locking semaphore, etc.
Good luck!
I think when we use Task.Run(), it remains in the same thread (Main thread) by default.
Yes I have already used job queue, it is OK.
If we use ConfigureAwait(false), we should care about threads.
Task.Run().ConfigureAwait(false)
My question was if I can use WWW or UnityWebRequest with async/await?
Can you use it? Sure.
Can you âawaitâ it? Not directly. Unity has not implemented either WWW or UnityWebRequest as an awaitable.
If you google for it youâll find some people implementing awaiters for UnityWebRequest. Like this one:
Though really, the awaiter pattern is pretty straight forward and you should be able to implement it yourself easily.
Both UnityWebRequest and WWW actually run asynchronously on other thread. When you use them from coroutine and do yield return, you kick them off on another thread and suspend the coroutine until request finishes. Once request finishes, the coroutine is continued and it executes on main thread, so it allows you to safely work with Unity APIs.
In only WWW and unityWebRequest, when I use yield return, the thread switches to another thread?
or whenever I use yield return (for example yield return StartCoroutine)?
yield return suspends the coroutine until âsomethingâ. If you yield return null, it is suspended until next frame.
If you yield return WWW or the AsyncOperation returned by UWRs SendWebReuest(), coroutine is suspended until request finishes.
As for threading, UnityWebRequest (and WWW) always perform request on a different thread, you can simply start them and on upcomming Update() calls check their status.