In one of my methods, I want to create a car like this:
public string[] CreateCar()
{
string[] wheels = CreateWheels();
// Also add motor and other stuff here
string[] motor = ...;
return new string[][]{ wheels, motor, ... };
}
Here four wheels a created and they don't depend on each other.
Hence, I can place them in multiple tasks, do be parallelised. (In my real code, this is not possible with a parallel-for loop)
public string[] CreateWheels()
{
Task FL = Task.Run(() => CreateWheel("front left");
Task FR = Task.Run(() => CreateWheel("front right");
Task BL = Task.Run(() => CreateWheel("back left");
Task BR = Task.Run(() => CreateWheel("back right");
// Here I really want to wait for all wheels to be created!
// STOP THE PROCESS HERE UNTIL ALL WHEELS ARE COMPLETED!!!
string[] wheels = await Wask.WhenAll(FL, FR, BL, BR);
return wheels;
}
And one single wheel is created something like that:
public string CreateWheel(string position)
{
// Here a wheel is created, whatever it takes :)
return "wheel " + position;
}
My problem now is the following:
In order to get the code compiled, it forces me to mark CreateWheels as an async-Method. Otherwise I cannot use await.
⇒ But this forces me to change its return-value to be a Task<string[]>
⇒ However, then I need to put an await in front of CreateWheels() in the CreateCar-Method in order to get the string array and not the Task itself
⇒ Then the cycle repeats, since now, there is an await in the CreateWheels, forcing me to make it async ... and so on, and so on ...
This cycle repeats all the way up, until it finally comes to a void method, where you don't need to extract the return value with an await
What is the way out of this cycle, if I only want to wait for all wheels to be finished at the marked point?
CreateCaris a particularity demanding method then I don't see why you want to useTask.Runto execute it.string[] wheels = Task.WhenAll(FL, FR, BL, BR).Result;should work.Resulton a task IMO.