Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a `when()` statement or some equivalent in C#?

Tags:

c#

.net

Is there maybe something like a "when" statement in C#?

The reason I want this is because an if statement only checks once if a certain property is true at a particular time, but I want it to wait until the property is true.

Anybody know something I can do in C# that would be similar to a "when" statement?

like image 676
Sebastian Avatar asked Dec 13 '22 16:12

Sebastian


2 Answers

What you want is SpinWait

e.g. SpinWait.SpinUntil(() => condition);

It will sit there until it either times out (with your specified timeout) or the condition is met.

like image 151
gmn Avatar answered Dec 28 '22 02:12

gmn


There is no when control statement, but there are two options which might meet your needs:

You can use a while(predicate){} loop to keep looping until a condition is met. The predicate can be any expression which returns true/false - as long as the condition is true, it will loop. If you just want to wait without consuming too much CPU, you can Sleep() the thread within the loop:

while(name == "Sebastian")
{
    // Code to execute
    System.Threading.Thread.Sleep(1000);
}

If you property is a numeric range, you could use a for loop, but that doesn't sound like what you want.

like image 38
Peter Avatar answered Dec 28 '22 01:12

Peter