Share via


일정 기간 이후 비동기 작업 취소

작업이 완료될 때까지 대기하지 않으려는 경우 일정 기간 후에 CancellationTokenSource.CancelAfter 메서드를 사용하여 비동기 작업을 취소할 수 있습니다. 이 메서드는 CancelAfter 식으로 지정된 일정 기간 내에 완료되지 않은 연결된 작업의 취소를 예약합니다.

이 예제는 작업 목록 취소(C#)에서 개발된 코드에 추가되어 웹 사이트 목록을 다운로드하고 각 웹 사이트의 콘텐츠 길이를 표시합니다.

이 자습서에서는 다음 내용을 다룹니다.

  • 기존 .NET 콘솔 애플리케이션 업데이트
  • 취소 예약

필수 조건

이 자습서를 사용하려면 다음이 필요합니다.

애플리케이션 진입점 업데이트

기존 Main 메서드를 다음으로 바꿉니다.

static async Task Main()
{
    Console.WriteLine("Application started.");

    try
    {
        s_cts.CancelAfter(3500);

        await SumPageSizesAsync();
    }
    catch (OperationCanceledException)
    {
        Console.WriteLine("\nTasks cancelled: timed out.\n");
    }
    finally
    {
        s_cts.Dispose();
    }

    Console.WriteLine("Application ending.");
}

업데이트된 Main 메서드는 몇 가지 지침 메시지를 콘솔에 기록합니다. try-catch 내에서 CancellationTokenSource.CancelAfter(Int32) 호출은 취소를 예약합니다. 이렇게 하면 일정 기간 후에 취소하라는 신호가 전송됩니다.

다음으로, SumPageSizesAsync 메서드는 대기합니다. 예약된 취소보다 모든 URL이 더 빠르게 처리되면 애플리케이션이 종료됩니다. 그러나 모든 URL이 처리되기 전에 예약된 취소가 트리거되면 OperationCanceledException이 throw됩니다.

예제 애플리케이션 출력

Application started.

https://learn.microsoft.com                                       37,357
https://learn.microsoft.com/aspnet/core                           85,589
https://learn.microsoft.com/azure                                398,939
https://learn.microsoft.com/azure/devops                          73,663

Tasks cancelled: timed out.

Application ending.

전체 예제

다음 코드는 예제에 관한 Program.cs 파일의 전체 텍스트입니다.

using System.Diagnostics;

class Program
{
    static readonly CancellationTokenSource s_cts = new CancellationTokenSource();

    static readonly HttpClient s_client = new HttpClient
    {
        MaxResponseContentBufferSize = 1_000_000
    };

    static readonly IEnumerable<string> s_urlList = new string[]
    {
            "https://learn.microsoft.com",
            "https://learn.microsoft.com/aspnet/core",
            "https://learn.microsoft.com/azure",
            "https://learn.microsoft.com/azure/devops",
            "https://learn.microsoft.com/dotnet",
            "https://learn.microsoft.com/dynamics365",
            "https://learn.microsoft.com/education",
            "https://learn.microsoft.com/enterprise-mobility-security",
            "https://learn.microsoft.com/gaming",
            "https://learn.microsoft.com/graph",
            "https://learn.microsoft.com/microsoft-365",
            "https://learn.microsoft.com/office",
            "https://learn.microsoft.com/powershell",
            "https://learn.microsoft.com/sql",
            "https://learn.microsoft.com/surface",
            "https://learn.microsoft.com/system-center",
            "https://learn.microsoft.com/visualstudio",
            "https://learn.microsoft.com/windows",
            "https://learn.microsoft.com/maui"
    };

    static async Task Main()
    {
        Console.WriteLine("Application started.");

        try
        {
            s_cts.CancelAfter(3500);

            await SumPageSizesAsync();
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("\nTasks cancelled: timed out.\n");
        }
        finally
        {
            s_cts.Dispose();
        }

        Console.WriteLine("Application ending.");
    }

    static async Task SumPageSizesAsync()
    {
        var stopwatch = Stopwatch.StartNew();

        int total = 0;
        foreach (string url in s_urlList)
        {
            int contentLength = await ProcessUrlAsync(url, s_client, s_cts.Token);
            total += contentLength;
        }

        stopwatch.Stop();

        Console.WriteLine($"\nTotal bytes returned:  {total:#,#}");
        Console.WriteLine($"Elapsed time:          {stopwatch.Elapsed}\n");
    }

    static async Task<int> ProcessUrlAsync(string url, HttpClient client, CancellationToken token)
    {
        HttpResponseMessage response = await client.GetAsync(url, token);
        byte[] content = await response.Content.ReadAsByteArrayAsync(token);
        Console.WriteLine($"{url,-60} {content.Length,10:#,#}");

        return content.Length;
    }
}

참고 항목