Wait for x seconds in while loop c#

Viewed 11025

Im trying to make a simple application to learn some things in c# (Visual Studio). For now i am building a music player, and one of the actions is fading out the music at the button click event.

I've got no problem with building a fade-out part, i made a while loop and put the volume down with 1% eacht time the loop is running. Also i update a label with the fade value.

Only problem is, for slowing down the fading i'm using the Thread.Sleep event, and that part is freezing my application, and also is blocking any updates to my text label with the fade value.

The fading is working fine, so the only part I have to work on is another option to build some delay in. On some topics over here i did read about the timer, and i added a timer component in Visual Studio. Only problem, I am new to c# and don't know how to use it correctly in this while loop.

Can anybody give me some help?

The current code is:

    private void BtnPodiumtune1Fadeout_Click(object sender, EventArgs e)
    {
        PlayerPodiumtune1.settings.volume = 100;
        fade1 = 100;
        while (fade1 != -1)
        {
            PlayerPodiumtune1.settings.volume = fade1;
            Fadelevel1.Text = fade1.ToString();
            System.Threading.Thread.Sleep(30);
            fade1 = fade1 - 1;
        }
        PlayerPodiumtune1.Ctlcontrols.stop();
    }
2 Answers

You could use a pattern like this instead of a timer. A timer is a fine way to go, just throwing this option out there:

private async void button_Click(object sender, EventArgs e)
{
  if (Monitor.TryEnter(sender))
  {
    int fade1 = 1000;
    while (fade1 != -1)
    {
      await Task.Delay(30);
      fade1--;
    }
  }
}

So sender is the button, and Monitor.TryEnter prevents the function from being run again until the function is done. async tells the framework that this function can be executed asynchronously and is necessary for await. await returns control of the thread to the UI until the task is done.

PS--You're going to need something like Monitor.TryEnter to prevent re-entrancy in a timer-based solution as well, by the way.

This is a Console Application in C#:

using System;

namespace WaitAsync
{
    class Program
    {

        static void Main(string[] args)
        {
            bool ok = false;

            Console.Write("EnterTime (Seconds): ");
            int time = Convert.ToInt32(Console.ReadLine()) * 1000;

            while (ok != true)
            {
                System.Threading.Thread.Sleep(time);
                ok = true;
                Console.WriteLine("Waiting Time Just Finished");
            }
            Console.ReadLine();
        }
    }
}
Related