Home > other >  Using a while loop and continuing to execute the lines below C# Console
Using a while loop and continuing to execute the lines below C# Console

Time:11-01

Someone can help me? I have a little doubt how I can load a while(true)) in the c# console and continue loading the code from the lines below (continuing to perform the loop). (I know the loop is infinite but does anyone know or can help me with a solution?)

I want the console to be constantly changing the title to something "Random" so I use the loop.

while(true)
{
    Thread.Sleep(100);
    Random rnd = new Random();
    int[] numbs = new int[100];
    string[] palavras = { "hi", "2", "bye", "ok", "nah", "idk", "done", "local", "can you", "bruh", "example", "nope", "hehe" };
    int index = rnd.Next(palavras.Length);
    Console.Title = (palavras[index]);             
}

CodePudding user response:

You should use Microsoft's Reactive Framework (aka Rx) - NuGet System.Reactive and add using System.Reactive.Linq; - then you can do this:

Random rnd = new Random();
string[] palavras = { "hi", "2", "bye", "ok", "nah", "idk", "done", "local", "can you", "bruh", "example", "nope", "hehe" };
IDisposable subscription =
    Observable
        .Interval(TimeSpan.FromMilliseconds(100.0))
        .Select(x => palavras[rnd.Next(palavras.Length)])
        .Subscribe(x => Console.Title = x);
        
Console.WriteLine("This code continue to run while the title updates.");

When you want the titles to stop updating, just call subscription.Dispose().

  •  Tags:  
  • c#
  • Related