개발자 블로그

Static 메서드와 Instance 메서드의 선택 기준 본문

c#

Static 메서드와 Instance 메서드의 선택 기준

youngsunny 2024. 6. 19. 00:38
using System;
using System.Threading;
using System.Threading.Tasks;

public class TaskExample
{
    private static CancellationTokenSource cts;

    public static async Task Main()
    {
        cts = new CancellationTokenSource();
        var task = Task.Run(() => DoWork(cts.Token), cts.Token);

        // 5초 후 작업 중단 요청
        await Task.Delay(5000);
        cts.Cancel();
        await task;
        Console.WriteLine("Task has been safely stopped.");
    }

    private static async Task DoWork(CancellationToken token)
    {
        while (!token.IsCancellationRequested)
        {
            for (int i = 1; i <= 10; i++)
            {
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("Cancellation requested. Exiting...");
                    return;
                }

                Console.WriteLine($"Task is working on step {i}...");
                await Task.Delay(500); // 예제에서는 500ms 대기
            }
        }
    }
}

https://chatgpt.com/share/cf4259be-1054-43b2-8b26-f31a1981214d

 

ChatGPT

A conversational AI system that listens, learns, and challenges

chatgpt.com

 

'c#' 카테고리의 다른 글

1. 동기 비동기 차이  (0) 2024.06.29
데이터 타입(value type, reference type)(정리중)  (0) 2024.06.18