C#

콘솔에서 비동기 입력 받기(예로 추첨 프로그램)

기공이 2016. 4. 11. 16:24

콘솔에서 키 입력을 비동기 적으로 받는 코드입니다.

기본적인 코드는


1
2
3
4
Task.Factory.StartNew(() =>
    {
        Console.ReadKey()
    });
cs


이런 형식인데 Console 클래스는 ReadKey()에서 ConsoleKeyInfo 구조체를 반환합니다.

ConsoleKeyInfo 의 Key 해당 구조체가 나타내는 키 값을 가져오는데 이는 ConsoleKey 에 매칭됩니다.


이를 바탕으로 추첨 프로그램을 만들 수 있습니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Program
{
    static bool exit = false;
    static void Main(string[] args)
    {
        Random rand = new Random((int)DateTime.Now.Ticks);
        int i = 0;
 
        // 비동기 입력
        Task.Factory.StartNew(() =>
        {
            while (Console.ReadKey().Key != ConsoleKey.Q) ;
            exit = true;
        });
 
        while (!exit)
        {
            i = rand.Next(1, 100000);
            Console.WriteLine("{0}", i.ToString("D5")); // D5는 Decimal 5자리로 나타낸다는 뜻
            System.Threading.Thread.Sleep(50);
            Console.Clear();
        }
        Console.Clear();
        i = rand.Next(1, 4000); // 1 ~ 4000 중 임의의 수 반환
        Console.WriteLine("{0}", i.ToString("D5"));
    }
}
cs