-
-
Notifications
You must be signed in to change notification settings - Fork 146
/
Program.cs
97 lines (76 loc) · 3.1 KB
/
Program.cs
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// Copyright (c) .NET Foundation and Contributors
// See LICENSE file in the project root for full license information.
//
using System.Diagnostics;
using System.Threading;
namespace Basic_Threading
{
public class Program
{
public static void Main()
{
ServerClass serverObject = new ServerClass();
// Create the thread object, passing in the
// serverObject.InstanceMethod method using a
// ThreadStart delegate.
Thread instanceCaller = new Thread(
new ThreadStart(serverObject.InstanceMethod));
// Start the thread.
instanceCaller.Start();
Debug.WriteLine(
"The Main() thread calls this after "
+ "starting the new InstanceCaller thread.");
// Create the thread object, passing in the
// serverObject.StaticMethod method using a
// ThreadStart delegate.
Thread staticCaller = new Thread(
new ThreadStart(ServerClass.StaticMethod));
// Start the thread.
staticCaller.Start();
Debug.WriteLine(
"The Main() thread calls this after "
+ "starting the new StaticCaller thread.");
// Create another thread object, using a lambda expression.
// Without retaining any reference to it and starting it immidiatly
new Thread(() =>
{
Debug.WriteLine(
">>>>>> This inline code is running on another thread.");
// Pause for a moment to provide a delay to make
// threads more apparent.
Thread.Sleep(6000);
Debug.WriteLine(
">>>>>> The inline code by the worker thread has ended.");
}).Start();
Debug.WriteLine(
"The Main() thread calls this after "
+ "starting the new inline thread with the lambda expression.");
Thread.Sleep(Timeout.Infinite);
}
public class ServerClass
{
// The method that will be called when the thread is started.
public void InstanceMethod()
{
Debug.WriteLine(
">> ServerClass.InstanceMethod is running on another thread.");
// Pause for a moment to provide a delay to make
// threads more apparent.
Thread.Sleep(3000);
Debug.WriteLine(
">> The instance method called by the worker thread has ended.");
}
public static void StaticMethod()
{
Debug.WriteLine(
">>>> ServerClass.StaticMethod is running on another thread.");
// Pause for a moment to provide a delay to make
// threads more apparent.
Thread.Sleep(5000);
Debug.WriteLine(
">>>> The static method called by the worker thread has ended.");
}
}
}
}