15/10/12 19:51:26.84 wjSQdsNO.net
>>160 たぶんやりたいことは、こんなところか。
private CancellationTokenSource cancelSource;
private void button1_Click( object sender , EventArgs e ) {
if( this.cancelSource != null )
this.cancelSource.Cancel(); // まだキャンセルされてなければキャンセル要求
this.button1.Enabled = false;
this.cancelSource = new CancellationTokenSource();
var token = this.cancelSource.Token;
Task.Factory.StartNew( () =>{
for( int i = 0; i < 100000; i++ ){
token.ThrowIfCancellationRequested();
Thread.Sleep( 100 );
}
} , token )
.ContinueWith( task => {
// 継続タスク(UIスレッドに切り替わって実行される)
// キャンセルされようとも正常に完了しようとも、例外が発生しても実行される。
this.button1.Enabled = true;
} , TaskScheduler.FromCurrentSynchronizationContext() );
}
private void button2_Click( object sender , EventArgs e ) {
if( this.cancelSource != null ) {
this.cancelSource.Cancel(); // キャンセル要求
this.cancelSource = null;
}
}