2

Hi i have this c# windows form application and i have this thread under the InitializeComponent()

now it runs continuously after application start now i want is to run that every 20 minutes after a run for example

run
Wait 20 m.
run 
wait 20 m.
run
.... 

here's the code

Thread thread = new Thread(() =>
                {
                    while (true)
                    {

                       //some process

                    }
                });
                thread.IsBackground = true;
                thread.Start();

I remove the code inside.

what i'm facing is the application is taking too much of the computer network beacause the thread runs a query every milisec so i need only to run the thread every 20minutes after every runs Hope i make my explanation clear

Thankyou in advance.

Kiffer Van
  • 232
  • 4
  • 15
  • 3
    Check the `Thread.Sleep()` method documentation – BlueStrat Jun 09 '20 at 00:46
  • Consider a `Timer`. It certainly wouldn't constitute a "major change" - probably < 10 lines of code changed. – mjwills Jun 09 '20 at 01:36
  • because there's i thread per job item in the application so if the'res 100 item i will not use hundred of timer, each item has different time thats why, sorry i did not meansion it earlyer –  Kiffer Van Jun 09 '20 at 01:39
  • sorry i just can't explain it correctly, it is also running on production already its also one of the reason –  Kiffer Van Jun 09 '20 at 02:21

1 Answers1

4

You can use Task.Delay and asynchronous lambda:

Thread thread = new Thread(async () =>
            {
                while (true)
                {
                    await Task.Delay(TimeSpan.FromMinutes(20));
                    //some process
                    Console.WriteLine("1");

                }
            });

Or use one of .NET Timer's to execute method on specified intervals.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132