I have a switch-statement and three case's. But now I need the switch to start over when it's done with case 2. Ive tried a while loop but it dosen't seems to help. Is there any other way?
switch (row)//Färgalternativ
{
while(true)
{
case 0:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 1:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Green;
break;
}
}
FrohikkiPosted Sep 16, 2012, 9:15 AM
FrohikkiPosted Sep 16, 2012, 9:04 AM
theLizardPosted Sep 16, 2012, 5:55 AM
Where does row get changed?
Even if the row is changed in case 2 from 2 to 0, the loop will go on for ever in case 0, however, entry into the loop would have to be at case 2 level for this scenario after this, case 2 or 1 will never be seen .
The only way I see to achieve what you want is by creating a thread to watch for the change in row value in which case you do not need a while loop for the switch.
If you implement the thread correctly, whenever row value changes, the switch will work on its own.
The switch code will need to be inside the thread object's execute method in a loop that checks for the thread objects terminate condition, you should also have a lastRow var so that you do not execute the switch unless row != lastRow.
while(!thread.terminate)
{
if(callerthread.row != lastRow)
{
synhcronize(whichColor);
}
}
private void whichColor()
{
switch(callerthread.row)
{
case 0:
callerthread.Console.ForegroundColor = ConsoleColor.Green;
break;
}
}
Now I am the first to tell you that I have never used threading objects in c# so the example code is only pseudo.code (the type of code I would use in C++) nothing more, maybe Vulpes can guid you more on threads in c#
I also do not know if you can create other threads in console apps
VulpesPosted Sep 16, 2012, 4:35 AM
FrohikkiPosted Sep 16, 2012, 3:59 AM
theLizardPosted Sep 15, 2012, 8:26 PM
As soon as you get into the while loop (will remain there for ever -- while(true)) the value of row will never change and repeat the same case forever.
If the switch relies on the value of row, row value must have some way to change it's value even if it is the same value outside of the while loop.
For the op to get the result wanted, the while loop must be done at the source of row change or at least where the row change is triggered.
Edit: One other way would be to put the loop into a new thread object that looks at the value of a global variable which could be set at the row change event but you would need to know about thread objects and synchronization to do this.
Of course I could be missing something and could wrong.
VulpesPosted Sep 15, 2012, 6:38 PM
while(true)
{
bool reswitch = false;
switch (row)//Färgalternativ
{
case 0:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
case 1:
Console.ForegroundColor = ConsoleColor.Magenta;
break;
case 2:
Console.ForegroundColor = ConsoleColor.Green;
reswitch = true;
break;
}
if (!reswitch) break;
}