Task クラスによる並列処理(キャンセル付)
public class TaskExample1 : Form
{
public CancellationTokenSource m_cancellation = null;
private void buttonCancel_Click( object sender, EventArgs e )
{
if( m_cancellation != null )
{
if( m_cancellation.IsCancellationRequested == false )
{
m_cancellation.Cancel();
}
}
}
private void AddOpacity( int nOpacity )
{
this.Opacity = nOpacity / 100.0;
}
private void buttonRun_Click( object sender, EventArgs e )
{
m_cancellation = new CancellationTokenSource();
UpdateOpacity cb = AddOpacity;
Task taskOpacity = Task.Factory.StartNew( () =>
{
int nOpacity = 0;
do
{
++ nOpacity;
Invoke( cb, nOpacity );
System.Threading.Thread.Sleep( 5 );
}while( nOpacity < 100 && m_cancellation.IsCancellationRequested == false );
} );
taskOpacity.ContinueWith( t =>
{
Invoke( cb, 100 );
m_cancellation.Dispose();
m_cancellation = null;
} );
}
}