성태의 닷넷 이야기
홈 주인
모아 놓은 자료
프로그래밍
질문/답변
사용자 관리
사용자
메뉴
아티클
외부 아티클
유용한 코드
온라인 기능
MathJax 입력기
최근 덧글
[정성태] 질문이 잘 이해가 안 됩니다. 우선, 해당 소스코드에서 ILis...
[양승조
] var대신 dinamic으로 선언해서 해결은 했습니다. 맞는 해...
[양승조
] 또 막혔습니다. ㅠㅠ var list = props[i].Ge...
[양승조
] 아. 감사합니다. 어제는 안됐던것 같은데....정신을 차려야겠네...
[정성태] "props[i].GetValue(props[i])" 코드에서 ...
[정성태] 저렇게 조각 코드 말고, 실제로 재현이 되는 예제 프로젝트를 압...
[정성태] Modules 창(Ctrl+Shift+U)을 띄워서, 해당 Op...
[정성태] 만드실 수 있습니다. 단지, Unity 엔진 내의 스크립트와 W...
[공진영] 안녕하세요 좋은글 감사합니다. 현재 제가 wpf로 관제 모...
[정성태] The Windows Registry Adventure #1: ...
글쓰기
제목
이름
암호
전자우편
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>
첨부파일
스팸 방지용 인증 번호
1910
(왼쪽의 숫자를 입력해야 합니다.)