-1

I have something like :

 private void Form1_Load(object sender, EventArgs e)
        {
            Hide();
            string ngdx = "*ngdx";
            string atdx = "*atdx";

            for (;;)
            {
                try
                {

                    string[] convertngdx = Directory.GetFiles("D:\\folder", ngdx);
                    string[] convertatdx = Directory.GetFiles("D:\\folder", atdx);


                    foreach (var convertngd in convertngdx)
                    {
                        File.Move(convertngd, Path.ChangeExtension(convertngd, ".ngd"));
                    }
                    foreach (var convertatd in convertatdx)
                    {
                        File.Move(convertatd, Path.ChangeExtension(convertatd, ".atd"));
                    }
                }
                catch
                {

                }
            }
        }

I start my app and every time a .ngdx and .atdx file is send to the folder it automatically converts it to .ngd and .atd.

My problem is that it instantly converts them , and I want it to wait for a second before converting them.

I used System.Threading.Thread.Sleep(1000); but it doesn't quite seem to work,I think because when I run my app the System.Threading.Thread.Sleep(1000); is called and then after a second it is never called again.

The idea is every time a new .ngdx or .atdx is send to the folder I want it to wait for a second before converting them.

Martin Eden
  • 6,143
  • 3
  • 30
  • 33
John Pietrar
  • 513
  • 7
  • 19
  • Put the sleep in the for loop? – Jacobr365 Jul 12 '16 at 13:32
  • 4
    Sitting in a loop like this is going to tie up the UI thread (this looks like a WinForms application...). Have you considered using a [`FileSystemWatcher`](https://msdn.microsoft.com/en-us/library/system.io.filesystemwatcher(v=vs.110).aspx)? ([example](http://stackoverflow.com/a/721743/39709)) – Richard Ev Jul 12 '16 at 13:33
  • Very good idea @RichardEverett – wake-0 Jul 12 '16 at 13:33
  • I'd use a timer that is started when the method is called and the conversion is done in the timer's callback/elapsed event. The timer won't block the UI thread. – keyboardP Jul 12 '16 at 13:36
  • A debugger breakpoint is an excellent way to produce delays that are **exactly** as long as you need them to be. – Hans Passant Jul 12 '16 at 14:05
  • 1
    @RichardEverett I did not know about the `FileSystemWatcher` thank you a lot for telling me about it :) you can tag it as an answer so I can close this question :) – John Pietrar Jul 13 '16 at 07:06

1 Answers1

3

As an alternative to using an infinite for loop (which will tie up the UI thread) you could use a FileSystemWatcher. (example)

Community
  • 1
  • 1
Richard Ev
  • 52,939
  • 59
  • 191
  • 278