Keiishkii
❔ Running an awaitable async Task, but forcing it to run on a specific thread (main thread).
Hi everyone, I'm doing some work in Unity and am having an issue where some of the code that I want to run asynchronously is throwing an exception due to the requirement that it is called on the main thread. This code I would also like to be created as a lambda expression which I am passing as a parameter before its invoked / ran.
I'm still quite new to async so bare with me if I have some concepts wrong still, but I've been experimenting / looking into things a bit and have come up with the understanding that:
Can start the action, and the task that it returns can be correctly awaited for its completion, however I cannot find anything on how to force this task to be ran on the main thread.
Can take in a TaskScheduler as an input, and using
TaskScheduler.FromCurrentSynchronizationContext()
will force it to run on the main thread without causing any trouble within unity. However, it does not await correctly as from what I've read it does not recognise async lambdas, instead thinking there just synchronous. And skipping to the end pretty much immediately.
Hopefully this makes a bit of sense, having given the context, the main focus for my question is - Can you force an async Task to run on the main thread from inside another async Task. And if so what is the proper way to do this?2 replies