C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드
다음과 같은 질문이 있군요. ^^
Task 만들 때 넘겨주는 CancellationToken은 어디서 사용되는 건가요?
; https://www.sysnet.pe.kr/3/0/5157
위의 질문에서는 나오지 않았지만 현실적인 면에서 보면 CancellationToken은 비동기 작업을 취소하는 용도로 사용될 수 있습니다. 가령, 작업이 완료되기까지 꽤나 오래 걸리는 연산을 하는 경우,
using System;
using System.Numerics;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
LongWork(long.MaxValue - 1);
Console.ReadLine();
Console.WriteLine("End-of-work");
}
static async Task LongWork(long to)
{
Console.WriteLine("Starting...");
await Task.Factory.StartNew(() => GetSum(to));
Console.WriteLine("Completed");
}
static BigInteger GetSum(long last)
{
BigInteger sum = 0;
for (long i = 0; i < last; i ++)
{
i++;
sum += i;
}
return sum;
}
}
예제를 간단하게 만들기 위해 콘솔로 했지만, LongWork 작업을 윈도우 UI 응용 프로그램에서 "버튼"을 눌러 시작했다고 가정해 보겠습니다. 이럴 때 다른 버튼을 눌러 해당 작업을 취소하고 싶다면 어떻게 해야 할까요? 물론, 별도의 참조 객체를 넘겨서 Cancel 플래그를 추가해 구현하는 것도 가능하겠지만 마이크로소프트는 이런 경우에 대한 표준 작업을 CancellationTokenSource를 이용해 구현하도록 미리 준비해 두었습니다. 따라서 다음과 같이 구현하면 됩니다.
using System;
using System.Numerics;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
CancellationTokenSource tokenSource = new CancellationTokenSource();
LongWork(long.MaxValue - 1, tokenSource.Token);
Console.WriteLine("Press any key to cancel...");
Console.ReadLine();
tokenSource.Cancel();
Console.ReadLine();
Console.WriteLine("End-of-work");
}
static async Task LongWork(long to, CancellationToken token)
{
Console.WriteLine("Starting...");
await Task.Factory.StartNew(() => GetSum(to, token));
Console.WriteLine("Completed");
}
static BigInteger GetSum(long last, CancellationToken token)
{
BigInteger sum = 0;
for (long i = 0; i < last; i++)
{
if (token.IsCancellationRequested == true)
{
break;
}
i++;
sum += i;
}
return sum;
}
}
(
첨부 파일은 이 글의 예제 코드를 포함합니다.)
참고로, 좀 더 다양한 예제는 다음의 도움말에서 살펴볼 수 있습니다.
How to: Cancel a Task and Its Children
; https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/how-to-cancel-a-task-and-its-children
[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]