본문 바로가기

프로그래밍/C#

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();

}

}

}

반응형

'프로그래밍 > C#' 카테고리의 다른 글

C# 소켓 클라이언트 socket client  (0) 2019.03.24
C# 소켓 서버 socket server  (0) 2019.03.24
C# 타이머 Timer  (0) 2019.03.24
C# 재귀호출  (0) 2019.03.24
C# 정렬 sort  (0) 2019.03.24