an oversimplication in parts, but it’s useful to think of things in this way to get your head around it.
I’m hoping you understand coroutines…
Coroutines are Asyncronous functions.
Async functions are also Asyncronous functions.
The goal of an asyncronous function is to be able to split a function into pieces and run these pieces over time so as not to block the execution of the program (typically they are running in your main thread, and you want them to not block the main thread).
Unity Coroutines use Yield to yield control
C# Async functions use Await to yield control
The Yield or the Await will specify when exactly they want control back… perhaps next frame, perhaps when a function has completed running, or a period of time has passed. When this condition is met, they are scheduled to continue execution and are given back control.
Tasks are multithreading, async await on its own is not.
Tasks are running in different threads (not always but you should think of them as if they are), and when you await them, you yield control while waiting for them to finish what they are doing on that thread before your async await code gets scheduled to continue it’s flow of execution.
Yes it will.
Telling a Thread to sleep freezes whatever thread you are in for the specified amount of time, and you’re in the main thread, because your async function is running in the main thread.
Right, you’re awaiting it, which means you are yielding control for 3 seconds (until it is finished), so the main thread continues to run until those 3 seconds are up and the async function gets control back.
This is just a quirk of anonymous functions, it’s called Capture I think.
Your anonymous function is capturing the main thread because the function it is declared in is being run on the main thread.
If you simply Task.Run( ADedicatedFunction), which has a Thread.Sleep in it, it would not block the main thread, it would block the thread that it is running in, which would be a new thread.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class TestAsync : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
CountToTenAsync();
}
private async void CountToTenAsync()
{
Debug.Log("Starting...");
for (int i = 1; i <= 10; i++)
{
await Task.Run(OneSecondSleep);
Debug.Log(i);
}
Debug.Log("Finished...");
}
private void OneSecondSleep()
{
Thread.Sleep(1000);
}
}