- Home /
Synchronization in execution of methods of a class using co-routines.
I have a Class which has a method "ExecuteSync". The code snippet of the class containing the function is as follows:
public class MyTasksClass : Monobehaviour{
public void ExecuteSync(string actionName){
switch(actionName){
case "action1" :
StartCoroutine(ActionOne());
break;
case "action2" :
StartCoroutine(ActionTwo());
break;
}
}
IEnumerator ActionOne(){
Debug.Log("Action One Started");
int a = 0;
while(a<100){
yield return null;
}
Debug.Log("Action One Ended");
yield return null;
}
//Please note that these two methods are not related to one another.
IEnumerator ActionTwo(){
Debug.Log("Action Two Started");
int a = 500;
while(a<1000){
yield return null;
}
Debug.Log("Action Two Ended");
yield return null;
}
}
There is another class UIController from which we can call these methods like as follows:
public class UIController : Monobehaviour{
public MyTasksClass myTaskClass;
void Start(){
myTaskClass = FindObjectOfType<MyTasksClass>();
Debug.Log("Synchronous started");
myTaskClass.ExecuteSync(action1);
Debug.Log("Synchronous ended");
}
}
The expected output should print in this order:
Synchronous started
Action One Started
Action One Ended
Synchronous ended
But the actual output is as follows:
Synchronous started
Synchronous ended
Action One Started
Action One Ended
Is there any way to make it work in a Synchronous way to print the expected output ? Any help will be appreciated.
Answer by Leoo · Sep 21, 2016 at 03:08 PM
Well that's exactly how people would expect Coroutines to work.
Coroutines wont just stop your "Start" method for the frames they need to finish, that's just not how it works.
I would recommend to just keep all that logic in a separate function that handles what happens "after" the coroutine end, stay out of the "start" method.
IEnumerator ActionOne(){
Debug.Log("Action One Started");
int a = 0;
while(a<100){
yield return null;
}
CoroutineEnded("Action One Ended");
yield return null;
}
//Please note that these two methods are not related to one another.
IEnumerator ActionTwo(){
Debug.Log("Action Two Started");
int a = 500;
while(a<1000){
yield return null;
}
CoroutineEnded("Action Two Ended");
yield return null;
}
public void CoroutineEnded(string msg){
Debug.Log(msg);
}
Hi @Leoo Thank you for the prompt response.
What we want to achieve is that the log "Synchronous ended" should get printed only when the entire execution in "ExecuteSync" function gets completed.
Hi @Leoo that is exactly the same thing that happened previously. There is not much of any difference in the code execution.
I want to block the execution of Debug.Log("Synchronous ended"); unless and until myTaskClass.ExecuteSync(action1); gets completed.
and we cannot have the return type of 'ExecuteSync' as IEnumerator.