Home » c# » multithreading – C# for loop never executing from thread or async method-Exceptionshub

multithreading – C# for loop never executing from thread or async method-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have a pretty simplistic block of code that I need to run on a separate thread or async as it needs to wait some time each loop until it has spawned all boxes from the array.

I have tried so many techniques that seem to work everywhere else but I am dumbfounded as to my mistake.

When I remove the threading and async, and run the for loop without delays, it works, but since there is no delay, I get a cascade of boxes flying about. This won’t do.

Most simply put, I need to wait ‘some time’ each for loop before spawning the next box to allow the current box to move out of the way. I want to do this without blocking the main thread. However, when I use threading or async, the for loop simply never executes.

Does anyone see anything that would indicate why it won’t execute? My debug confirms that my List of boxes is not empty upon starting, meaning that the for loop meets the requirements to execute.

Here is my code:

    public void HandleBoxSpawnThread() {
        ThreadPool.QueueUserWorkItem(ImportBoxSpawn);
    }

    public void ImportBoxSpawn(object state) {

        Debug.Log("Spawning!");
        Debug.Log("Count: "+readFromList.finalBoxList.Count);
        for (int i = 0; i < readFromList.finalBoxList.Count; i++) { 
            geniLoc = GeniEntrance.position;
            geniLoc += new Vector3(UnityEngine.Random.Range(-0.5f, 0.5f), 2, 2);
            float width = readFromList.finalBoxList[i].w;
            float length = readFromList.finalBoxList[i].l;
            width = width/39.3701f;
            length = length/39.3701f;
            float height = UnityEngine.Random.Range(0.3f,0.5f)*length;//Random.Range(0.0762f, 0.762f)
            Box_random.transform.localScale = new Vector3(width,height,length);
            Box_random.GetComponent<Rigidbody>().mass = (length*width*height)*50;
            Instantiate(Box_random, geniLoc, Quaternion.identity,myGeniParent);
            Debug.Log("Spawning Box "+i+".");
            Thread.Sleep(1000);
            Debug.Log("End");
        }
    }

EDIT: Upon some more debugging and researching, it appears that using transforms…

geniLoc = GeniEntrance.position;

…does not work in separate threads in Unity3D. I switched to using a coroutine and got the behavior I wanted. Because this isn’t a complex calculation or something that I expect to happen a lot, I’m not as concerned about the execution cost. In more complex situations where a lot of computing is happening, the correct solution would be to have a call back to the main thread to manipulate the transforms from the second thread. Thanks everyone!

How to&Answers: