Answer the question
In order to leave comments, you need to log in
Stop if check for a while?
There are several ints that get random values all the time.
For example, at this moment
int 1 = 100
int 2 = 50
int 3 = 150
while (true)
{
if (int1 > 20)
{
//код
System.Threading.Thread.Sleep(200000);
}
if (int2 > 400)
{
//код
System.Threading.Thread.Sleep(200000);
}
if (int3 > 300)
{
//код
System.Threading.Thread.Sleep(200000);
}
}
Answer the question
In order to leave comments, you need to log in
It’s a little unclear what you need to get, if you need to check all the conditions, fulfill those that are suitable and then “sleep”, it’s better something like this (but the flows are more adequate)
while (true)
{
if (int1 > 20)
{
//код
}
if (int2 > 400)
{
//код
}
if (int3 > 300)
{
//код
}
System.Threading.Thread.Sleep(200000);
}
You just need to add an appropriate timeout to the test condition. For example, it can be done like this:
public class Checker {
const double _stdDelta = 10.0d;
Dictionary<string, DateTime> _dictionary = new Dictionary<string, DateTime>();
bool check( string input, double? delta = null ) {
if ( !_dictionary.ContainsKey( input ) ) {
_dictionary.Add( input, DateTime.Now );
return true;
}
var d = delta.HasValue ? delta.Value : _stdDelta;
if ( ( DateTime.Now - _dictionary[input] ).TotalSeconds > d ) {
_dictionary[input] = DateTime.Now;
return true;
}
return false;
}
public void CheckConditionByIfs( int condition ) {
if ( condition > 100 && check( "second_condition", 20.0d ) ) {
Console.WriteLine( "Second_condition met, custom timeout set." );
} else if ( condition > 20 && check( "first_condition" ) ) {
Console.WriteLine( "First_condition met, standard timeout set." );
} else {
Console.WriteLine( "Nothing." );
}
}
public void CheckConditionBySwitch( int condition ) {
switch ( condition ) {
case var _ when condition > 100 && check( "second_condition", 20.0d ):
Console.WriteLine( "Second_condition met, custom timeout set." );
return;
case var _ when condition > 20 && check( "first_condition" ):
Console.WriteLine( "First_condition met, standard timeout set." );
return;
}
Console.WriteLine( "Nothing." );
}
}
var rnd = new Random();
var values = new int[] { 10, 15, 20, 25, 30, 35, 40, 50, 60, 70, 80, 100, 150, 200 };
var c = new Checker();
int cnd;
while ( true ) {
cnd = values[rnd.Next( values.Length )];
Console.WriteLine( cnd );
if ( rnd.Next( 100 ) > 50 )
c.CheckConditionBySwitch( cnd );
else
c.CheckConditionByIfs( cnd );
Thread.Sleep( 1500 );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question