programing/C#

[C#]Threading.Timer 생성자.. CallBack

쪽제비 2016. 8. 29. 15:19

Timer에 각각 다른 인자를 전달하여 생성을 하려고 하였다.

그런데 CallBack만 사용해서는 인자 1개밖에 전달이 되지 않았다.

방법을 찾던 중 MSDN에 생성자 관련 예제가 있어 확인해보니 Class를 생성하여 여러개의 인자를 전달하지 않고도 

각각 다른 값을 가지고 Timer를 생성할 수 있었다.


출처 : https://msdn.microsoft.com/ko-kr/library/2x96zfy7(v=vs.110).aspx




기존 사용하던 소스 코드.


System.Threading.Timer TimerTest;


public MainForm()

{

InitializeComponent();

TimerTest = new System.Threading.Timer(testProc, "test", 1000, 10000);

}


private static testProc(object test)

{

MessageBox.Show(test.ToString());

}


위 처럼 할 경우 10초에 한번씩 "test" 라는 메시지 박스가 생성이 된다.

더 많은 인자가 필요해서 위의 출처에 따라 클래스를 만들고. Test를 진행해보았다.



    class Program

    {

        private static System.Threading.Timer[] testTimer;


        static void Main(string[] args)

        {

            testTimer = new Timer[3];


            testTimer[0] = new Timer(new TimerClass(1, "test1").TestCallBack, "object1", 1000, 1000);

            testTimer[1] = new Timer(new TimerClass(2, "test2").TestCallBack, "object2", 1000, 2000);

            testTimer[2] = new Timer(new TimerClass(3, "test3").TestCallBack, "object3", 1000, 3000);



            Thread.Sleep(10000);

        }

    }


    class TimerClass

    {

        private int value1;

        private string value2;

//각기 다른 값을 넣도록 생성자 정의.

        public TimerClass(int val1, string val2)

        {

            value1 = val1;

            value2 = val2;

        }

//Timer가 주기적으로 실행할 CallBack 함수.

        public void TestCallBack(object data)

        {

            Console.WriteLine("{0}   {1}   {2}", value1, value2, data.ToString());

        }

    }

이해가 쉽게 하기 위해 Console을 사용..



[결과]



내 프로젝트에 적용을 해서 진행해야 겠다. 끝 !