본문 바로가기

worklog/C#

Thread

Thread 정리

    Start a thread 

      • 일반 사용
        • new Thread(Work);
      • ThreadStart 사용
        • new Thread(new ThreadStart(Work));
      • 람다식 사용
        • new Thread(() => Work());

    Start a thread with parameter

      • ParameterizedThreadStart 사용
        • new Thread(new ParameterizedThreadStart(WorkWithParam));

    Start a thread with return value

      • 람다식 이용하여 Return Value 받기 (returnValue는 선언한 object 변수)
        • new Thread(() => { returnValue = ReturnableWork(); });      


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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
        public static class ThreadExam
        {
            public static void ThreadTest()
            {
                Thread thread;
 
                // Start a thread 
                new Thread(Work).Start();
                new Thread(() => Work()).Start();
                thread = new Thread(new ThreadStart(Work));
                thread.Start();
                thread.Join();
 
                // Start a thread with parameter
                thread = new Thread(new ParameterizedThreadStart(WorkWithParam));
                thread.Start("Parameters");
 
                // Start a thread with return value
                object returnValue = null;
                thread = new Thread(() => { returnValue = ReturnableWork(); });
                thread.Start();
                thread.Join();
                Console.WriteLine(returnValue);
            }
            
            public static void Work()
            {
                Console.WriteLine($"Execute Work() : ThreadId:{Thread.CurrentThread.ManagedThreadId}");
            }
 
            public static void WorkWithParam(object obj)
            {
                Console.WriteLine($"Execute Work(object) : object = {obj} : ThreadId:{Thread.CurrentThread.ManagedThreadId}");
            }
 
            public static object ReturnableWork()
            {
                Console.WriteLine($"Execute ReturnableWork() : ThreadId:{Thread.CurrentThread.ManagedThreadId}");
                return "ReturnValue";
            }
 
        }
cs