C#

C# sleep과 지연함수 (delay)

sheepone 2021. 6. 16. 10:04
반응형

sleep

  • 지정된 시간(밀리초) 동안 현재 스레드를 일시 중단합니다.
using System.Threading;
//...
Thread.Sleep(2000);
  • 실사용 예제
using System;
using System.Threading;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                Console.WriteLine("Sleep for 2 seconds.");
                Thread.Sleep(2000);
            }
            Console.ReadKey();
        }
    }
}

 

  • 결과

 

지연함수

  • UI 쓰레드까지 정지 되지 않고 지연 시키기
public void Delay(int ms)
{
    DateTime dateTimeNow = DateTime.Now;
    TimeSpan duration = new TimeSpan(0, 0, 0, 0, ms);
    DateTime dateTimeAdd = dateTimeNow.Add(duration);
    while (dateTimeAdd >= dateTimeNow)
    {
        System.Windows.Forms.Application.DoEvents();
        dateTimeNow = DateTime.Now;
    }
    return;
}
  • 실사용 예제
using System;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff"));
                Console.WriteLine("Sleep for 2 seconds.");
                Delay(2000);
            }
        }

        public void Delay(int ms)
        {
            DateTime dateTimeNow = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, ms);
            DateTime dateTimeAdd = dateTimeNow.Add(duration);
            while (dateTimeAdd >= dateTimeNow)
            {
                System.Windows.Forms.Application.DoEvents();
                dateTimeNow = DateTime.Now;
            }
            return;
        }
    }
}
  • 출력창 결과
2021-06-16 10:01:02:238
Sleep for 2 seconds.
2021-06-16 10:01:04:244
Sleep for 2 seconds.
2021-06-16 10:01:06:245
Sleep for 2 seconds.
2021-06-16 10:01:08:245
Sleep for 2 seconds.
2021-06-16 10:01:10:246
Sleep for 2 seconds.
반응형