C
C#9mo ago
Heroshrine

✅ Does supplying a task with a delegate / action run that action on the main thread?

I would think if I do this it would run the method on the task's thread, but online I seem to have found information that this is the correct way to retrieve information from a thread? If this doesn't work, what is the correct way to retrieve information from a worker thread?
8 Replies
Flash619
Flash6199mo ago
Tasks != Threads, multiple tasks may share the same thread based on the task scheduler configuration. Typically it is recommended to use tasks, allowing the task scheduler to delegate work to worker threads. If you absolutely must have thread isolation, you can use Thread instead of Task.
information that this is the correct way to retrieve information from a thread
What thread information are you trying to retrieve? Can you elaborate on your use case?
JakenVeina
JakenVeina9mo ago
let's assume for the moment that you're talking about Task.Run() because that's about the only scenario where any of your question makes sense Task.Run() is shorthand for dispatching an action to the ThreadPool, and synchronizing its completion with a Task keep in mind: a Task doesn't do anything it's a synchronization primitive like a semaphore or signal event there are other mechanisms for executing actions and synchronizing with Tasks, which DON'T use the ThreadPool and there's far more mechanisms for creating Tasks which have nothing to do with threads or actions or delegates at all
Heroshrine
Heroshrine9mo ago
ah, I had no idea. Yes I'm using Task.Run() which I know is shorthand for using the task factory. I'm only just starting to use Tasks and dip into multithreading. I mostly use unity so my c# experience isn't "classic" experience, but they told me to go here because this question isn't about unity. basically I have some work I'm doing by using Task.Run(). Right now I'm just checking in a loop to see when it's finished, but I would like to know if there is a more elegant or better way to get notified when the work is finished. I'm returning a Stack from the Task. Right now I'm saving a reference to the Task and in a loop checking if it is complete. if it is, grab the stack from the result of the task.
JakenVeina
JakenVeina9mo ago
well, that's definitely a new one yes, there is a more elegant way look into async/await
Heroshrine
Heroshrine9mo ago
I know about async/await. I don’t know how i would use it. Would I call an async method like a normal method, and have that await the task?
JakenVeina
JakenVeina9mo ago
yes
Accord
Accord9mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Heroshrine
Heroshrine9mo ago
thanks for the help. Got it working great 👍 Due to how the game engine unity work I'm still essentially checking a variable in an update loop, but that is now a bool instead of a reference to a task, and it seems to be faster as well.