C# 스레드 thread
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace thread
{
public class ServerClass
{
// The method that will be called when the thread is started.
public void InstanceMethod()
{
Console.WriteLine(
"ServerClass.InstanceMethod is running on another thread.");
// Pause for a moment to provide a delay to make
// threads more apparent.
Thread.Sleep(3000);
Console.WriteLine(
"The instance method called by the worker thread has ended.");
}
public static void StaticMethod(object obj)
{
CancellationToken ct = (CancellationToken)obj;
Console.WriteLine("ServerClass.StaticMethod is running on another thread.");
// Simulate work that can be canceled.
while (!ct.IsCancellationRequested)
{
Thread.SpinWait(50000);
}
Console.WriteLine("The worker thread has been canceled. Press any key to exit.");
Console.ReadKey(true);
}
}
class Program
{
static void Main(string[] args)
{
ServerClass serverObject = new ServerClass();
Thread InstanceCaller = new Thread(
new ThreadStart(serverObject.InstanceMethod));
InstanceCaller.Start();
Console.WriteLine("The Main() thread calls this after " + "starting the new InstanceCaller thread.");
CancellationTokenSource cts = new CancellationTokenSource();
Console.WriteLine("Press 'C' to terminate the application...\n");
Thread t1 = new Thread(() =>
{
if (Console.ReadKey(true).KeyChar.ToString().ToUpperInvariant() == "C")
cts.Cancel();
});
Thread t2 = new Thread(new ParameterizedThreadStart(ServerClass.StaticMethod));
t1.Start();
t2.Start(cts.Token);
t2.Join();
cts.Dispose();
}
}
}