Microsoft , cancelationTokenSource cancelationToken.
Microsoft
StackOverflow :
CancellationToken CancellationTokenSource- ?
, -, System.Threading.CancellationToken. Wait CancellationToken, .
, , . , , . , -.
, , -, BooleanFunction true, , , .. , , . , , , CancellationIsRequested.
:
, . , , , , , , System.Timer. , -
: buttonStartWait buttonCancelWait. StartWait Wait, CancelWait .
, buttonCancelWait , true.
( Ticks TimeSpan, )
private CancellationTokenSource tokenSource = null;
private async void OnButtonStartWait_clicked(object sender, ...)
{
this.buttonStartWait.Enabled = false;
TimeSpan waitTime = GetWaitTime();
this.tokenSource = new tokenSource(waitTime);
await this.Wait(this.TokenSource.Token);
this.buttonstartWait.Enabled = true;
}
private async Task<bool> Wait(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
DoSomethingShort();
DoSomethingLonger(token);
await Task.Run( () => DoSomethingLonger(token), token);
}
return token.IsCancellationRequested;
}
private async Task<bool> Wait(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
await Task.Wait(TimeSpan.FromSeconds(0.1), token;
}
return token.IsCancellationRequested;
}
private async void OnButtonCancelWait_clicked(object sender, ...)
{
if (this.TokenSource != null)
{
this.TokenSource.Cancel();
}
}