Search code examples
c#wpfcsvdelaysleep

C# Thread.Sleep(ms) Freezes UI and I can't use Alternative Options


I am Making C# WPF Application That contains CSV Writing.

But, I wanna give some delays. But When i use Thread.Sleep(ms), UI freezes and Windows says that This Program has been Stopped.

So, I found some Alternatives like

private static DateTime Delay(int MS)
     {
         DateTime ThisMoment = DateTime.Now;
         TimeSpan duration = new TimeSpan(0, 0, 0, 0, MS);
         DateTime AfterWards = ThisMoment.Add(duration);
         while (AfterWards >= ThisMoment)
         {
             if (System.Windows.Application.Current != null)
             {
                 System.Windows.Application.Current.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Background, new Action(delegate { }));
             }
             ThisMoment = DateTime.Now;
         }
         return DateTime.Now;
     }

But,when I use this method, The Program just Stops.

This is Button Code that makes, writes CSV File.

 private void button_Click(object sender, RoutedEventArgs e)
    {

        try
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"New.csv");
            int a = 1;
            file.WriteLine("Delta, Theta");
            while (a < 20)
            {

                file.WriteLine("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
                a++;
                file.Close();
                Thread.Sleep(3000);    //Delay(3000); When I use Alternative way.
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Broken", ex);
        }
    }

The Main Question that I want to know is how to delay some seconds without Freezing UI. Sorry for Bad Grammar.


Solution

  • Make your click handler async. Then you can use Task.Delay, which will not block the thread.

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            System.IO.StreamWriter file = new System.IO.StreamWriter(@"New.csv");
            int a = 1;
            file.WriteLine("Delta, Theta");
            while (a < 20)
            {
                file.WriteLine("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
                a++;
                file.Close();
                await Task.Delay(3000);
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Broken", ex);
        }
    }
    

    By the way, here's one way to fix your exception:

    private async void button_Click(object sender, RoutedEventArgs e)
    {
        const string fileName = @"New.csv";
        try
        {
            File.AppendAllText(fileName, "Delta, Theta");
            for (var a=1; a<20; a++)
            {
                var text = string.Format("{0}, {1}", TGLatestData.EegPowerDelta, TGLatestData.EegPowerTheta);
                File.AppendAllText(fileName, text);
                await Task.Delay(3000);
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException("Broken", ex);
        }
    }