성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 그냥 RSS Reader 기능과 약간의 UI 편의성 때문에 사용...
[이종효] 오래된 소프트웨어는 보안 위협이 되기도 합니다. 혹시 어떤 기능...
[정성태] @Keystroke IEEE의 문서를 소개해 주시다니... +_...
[손민수 (Keystroke)] 괜히 듀얼채널 구성할 때 한번에 같은 제품 사라고 하는 것이 아...
[정성태] 전각(Full-width)/반각(Half-width) 기능을 토...
[정성태] Vector에 대한 내용은 없습니다. Vector가 닷넷 BCL...
[orion] 글 읽고 찾아보니 디자인 타임에는 InitializeCompon...
[orion] 연휴 전에 재현 프로젝트 올리자 생각해 놓고 여의치 않아서 못 ...
[정성태] 아래의 글에 정리했으니 참고하세요. C# - Typed D...
[정성태] 간단한 재현 프로젝트라도 있을까요? 저런 식으로 설명만 해...
글쓰기
제목
이름
암호
전자우편
HTML
홈페이지
유형
제니퍼 .NET
닷넷
COM 개체 관련
스크립트
VC++
VS.NET IDE
Windows
Team Foundation Server
디버깅 기술
오류 유형
개발 환경 구성
웹
기타
Linux
Java
DDK
Math
Phone
Graphics
사물인터넷
부모글 보이기/감추기
내용
<div style='display: inline'> <h1 style='font-family: Malgun Gothic, Consolas; font-size: 20pt; color: #006699; text-align: center; font-weight: bold'>C# - 비동기 호출을 취소하는 CancellationToken의 간단한 예제 코드</h1> <p> 다음과 같은 질문이 있군요. ^^<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > Task 만들 때 넘겨주는 CancellationToken은 어디서 사용되는 건가요? ; <a target='tab' href='http://www.sysnet.pe.kr/3/0/5157'>http://www.sysnet.pe.kr/3/0/5157</a> </pre> <br /> 위의 질문에서는 나오지 않았지만 현실적인 면에서 보면 CancellationToken은 비동기 작업을 취소하는 용도로 사용될 수 있습니다. 가령, 작업이 완료되기까지 꽤나 오래 걸리는 연산을 하는 경우,<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > 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; <span style='color: blue; font-weight: bold'>for (long i = 0; i < last; i ++) { i++; sum += i; }</span> return sum; } } </pre> <br /> 예제를 간단하게 만들기 위해 콘솔로 했지만, LongWork 작업을 윈도우 UI 응용 프로그램에서 "버튼"을 눌러 시작했다고 가정해 보겠습니다. 이럴 때 다른 버튼을 눌러 해당 작업을 취소하고 싶다면 어떻게 해야 할까요? 물론, 별도의 참조 객체를 넘겨서 Cancel 플래그를 추가해 구현하는 것도 가능하겠지만 마이크로소프트는 이런 경우에 대한 표준 작업을 CancellationTokenSource를 이용해 구현하도록 미리 준비해 두었습니다. 따라서 다음과 같이 구현하면 됩니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > using System; using System.Numerics; using System.Threading; using System.Threading.Tasks; class Program { static async Task Main(string[] args) { <span style='color: blue; font-weight: bold'>CancellationTokenSource tokenSource = new CancellationTokenSource();</span> LongWork(long.MaxValue - 1, <span style='color: blue; font-weight: bold'>tokenSource.Token</span>); Console.WriteLine("Press any key to cancel..."); Console.ReadLine(); <span style='color: blue; font-weight: bold'>tokenSource.Cancel();</span> Console.ReadLine(); Console.WriteLine("End-of-work"); } static async Task LongWork(long to, <span style='color: blue; font-weight: bold'>CancellationToken token</span>) { Console.WriteLine("Starting..."); await Task.Factory.StartNew(() => GetSum(to, <span style='color: blue; font-weight: bold'>token</span>)); Console.WriteLine("Completed"); } static BigInteger GetSum(long last, <span style='color: blue; font-weight: bold'>CancellationToken token</span>) { BigInteger sum = 0; for (long i = 0; i < last; i++) { <span style='color: blue; font-weight: bold'>if (token.IsCancellationRequested == true) { break; }</span> i++; sum += i; } return sum; } } </pre> <br /> (<a target='tab' href='https://www.sysnet.pe.kr/bbs/DownloadAttachment.aspx?fid=1449&boardid=331301885'>첨부 파일은 이 글의 예제 코드를 포함</a>합니다.)<br /> <br /> 참고로, 좀 더 다양한 예제는 다음의 도움말에서 살펴볼 수 있습니다.<br /> <br /> <pre style='margin: 10px 0px 10px 10px; padding: 10px 0px 10px 10px; background-color: #fbedbb; overflow: auto; font-family: Consolas, Verdana;' > How to: Cancel a Task and Its Children ; <a target='tab' href='https://learn.microsoft.com/en-us/dotnet/standard/parallel-programming/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</a> </pre> </p><br /> <br /><hr /><span style='color: Maroon'>[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]</span> </div>
첨부파일
스팸 방지용 인증 번호
1520
(왼쪽의 숫자를 입력해야 합니다.)