Reputation: 5
my android app running slow.Operation like Navigation, is particularly very slow.i used timer by below codes.now i want stop timer when i click button ?how do it
void ChangedData()
{
Task.Delay(500).ContinueWith(t =>
{
ChangedData();
}, TaskScheduler.FromCurrentSynchronizationContext());
}
Upvotes: 0
Views: 1068
Reputation: 1382
Create a CancellationTokenSource somewhere in your code.
var _cts = new System.Threading.CancellationTokenSource();
Then call Task.Delay with CancellationToken pass in the method.
Task.Delay(500, _cts.Token)
To cancel the task, just call Cancel method of the CancellationTokenSource
_cts.Cancel();
When the task is cancelled, it will throw TaskCanceledException. Please remember to catch the exception.
try
{
Task.Delay(500, _cts.Token).ContinueWith(t =>
{
ChangedData();
}, TaskScheduler.FromCurrentSynchronizationContext());
}
catch (TaskCanceledException ex)
{
// Handle when task is cancelled.
}
Upvotes: 0
Reputation: 89082
using System.Timers;
Timer timer = new Timer(500);
timer.Elapsed += (sender, e) => { ChangedData(); };
timer.Start();
// to stop the Timer
timer.Stop();
Upvotes: 1