public class CancelationTokenTest
{
public void testmethod2_multicancel()
{
var cancelsrc = new CancellationTokenSource();
Task k1 = Task.Run( async ()=>
{
while(true)
{
await Task.Delay(1200);
Console.WriteLine("k1 Done");
cancelsrc.Token.ThrowIfCancellationRequested(); // 여시서 토큰 상태 확인
}
}, cancelsrc.Token );
Task k2 = Task.Run( async ()=>
{
while(true)
{
await Task.Delay(1100);
Console.WriteLine("k2 Done");
cancelsrc.Token.ThrowIfCancellationRequested();
}
}, cancelsrc.Token );
//await Task.Delay( 5000 );
Thread.Sleep( 5000 );
Console.WriteLine("cancel is started");
cancelsrc.Cancel(); // 여기서 토큰 상태 취소로 바꿈.
Console.WriteLine("Cancel done");
Thread.Sleep( 5000 );
}
public void testmethod()
{
var cancelSource = new CancellationTokenSource();
Task foo = Foo(cancelSource.Token);
Thread.Sleep( 3000 );
Console.WriteLine( "cancel" );
cancelSource.Cancel();
Thread.Sleep( 3000 );
}
async Task Foo( CancellationToken cancellationToken )
{
int counter = 0;
try
{
for ( int i = 0 ; i < 10 ; i++ )
{
Console.WriteLine( i );
await Task.Delay( 500 );
cancellationToken.ThrowIfCancellationRequested();
}
}
catch ( Exception ex )
{
Console.WriteLine( "Exception" );
Console.WriteLine( counter );
counter++;
}
}
}
댓글 없음:
댓글 쓰기