How to add a time delay to an action

18,895

Solution 1

You can do it in two ways, for projects under .Net 4.0. Use Thread.Sleep method.

Thread.Sleep(int value or TimeSpan here)

for projects over or exactly .Net 4.0, you may use Task.Delay

Task.Delay(10).Wait();

await Task.Delay(10); // for .Net 4.5

Solution 2

using System.Threading; Thread.Sleep(x); // put your time in millis here

Doing the above will pause execution of your thread for however long you specify.

Share:
18,895
Dlorwisdom
Author by

Dlorwisdom

Currently studying C++, and C# languages. My current goals are to get in to Digital Signal Processing so I can develop instruments and tools for musicians. Im fairly good with HTML, CSS and JavaScript. Im still a very beta programmer but growing better everyday

Updated on July 18, 2022

Comments

  • Dlorwisdom
    Dlorwisdom almost 2 years

    So I am writing a small slot machine application for my C# class, I have the slot machine coded fairly well, but I was wondering how I would go about adding a time delay to actions. So that as my loop ran through I could pause at the end of each iteration, thereby creating a visual update of each slot on my machine for the user to watch

    Im not asking for code or a loop on how to achieve this, I can figure that out myself. I just need the method for setting time delays and the parameters of said method.

  • Dlorwisdom
    Dlorwisdom over 9 years
    Thank you!!! So much!!! We haven't covered this in our book but I knew there was a way!
  • DevEstacion
    DevEstacion over 9 years
    You're welcome @Dlorwisdom
  • Alexei Levenkov
    Alexei Levenkov over 9 years
    @Dlorwisdom Thread.Sleep is an interesting suggestion for something that clearly deal with UI... Make sure to ignore that part of answer (if you can't go async route - search for Timer).