C Amr Moneim C Amr Moneim - 2 months ago 8
C# Question

how to make loop stop with time?

i have loop for something but i want to stop after 5 mins

while (loop)
{
if (Name == null)
{
CheckName = false;
break;
}
}


i want to loop and then after some time finish the loop to do something else

Answer

The classical way is:

Stopwatch sw = new Stopwatch();
sw.Start();
while (sw.Elapsed.TotalMinutes <= 5)
{ 
    // do something
}
sw.Stop();

Another way would be:

var cancellation = new CancellationTokenSource(TimeSpan.FromMinutes(5));
while (!cancellation.IsCancellationRequested)
{
    // do something
}

I would highly recommend executing this in a background thread using Task. A method that runs for 5 mins is going to freeze the UI (If any).