0

I created a list of strings with .txt files and then checked if the files exist.

On top of that I want the tag to show the files the foreach is going through.

Tried thread.Sleep but the whole app freezes. I am in WPF and the following code I use.

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            List<string> test = new List<string>();
            test.Add(@"Files\file1.txt"); test.Add(@"Files\file2.txt"); test.Add(@"Files\file3.txt");

            foreach(string t in test)
            {
                Label2.Content = t;

                System.Threading.Thread.Sleep(1000);
                if (File.Exists(t))
                {
                    Label2.Content = "yea!";
                }
            }            
        }
Instint
  • 1
  • 1
  • What purpose is the line of code…`System.Threading.Thread.Sleep(1000);` … serving? If you want to “read” the contents of each file, you will need to open the file and read it. I suggest you look at the [StreamReader](https://learn.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=net-5.0) class. Your code does not appear to be reading the files. I suggest you peruse the SO [tour] section as it shows how SO works. The [ask] section may help. In addition, you may find the SO [Asking](https://stackoverflow.com/help/asking) section useful. – JohnG May 21 '21 at 23:36
  • You're blocking the main thread, so the UI can't update until the method returns. See duplicate for how to move the logic into a background thread. That said, in the code you posted, you could just replace the `System.Threading.Thread.Sleep(1000);` statement with `await Task.Delay(1000);` and that would fix everything (you have to add `async` to the method declaration to do that). – Peter Duniho May 21 '21 at 23:38
  • But, why are you putting that delay in there? I'm curious. As other's have pointed out, calling `Sleep` on the UI thread (particularly in a loop) never turns out well. But, even if you await Task.Delay, you are still introducing needless delay in your app. Do you have a reason? – Flydog57 May 22 '21 at 00:16
  • @Flydog57 I want it to read the filenames and print each filename in a tag while the foreach is running. More than anything it is a checker. – Instint May 22 '21 at 00:33

0 Answers0