I want to use System.Timer in my Xamarin Forms based project. I am actually converting my Xamarin iOS project to Xamarin Formbased project. My Xamarin iOS project has all code for Timer using System.Timer
aTimer = new Timer (tm);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler (OnTimedEvent);
aTimer.Enabled = true;
aTimer.Start ();
When i try to use the same code in Xamarin Forms project it is giving error. First of all
using System.Timers;
It says: The type or namespace name Timers does not exist in the namespace System. Are you missing a assembly reference?
Does Xamarin iOS System different than Xamarin Forms System reference?
PCL projects do not support System.Timer.
Xamarin Forms has a built in Timer to help workaround this limitation
Device.StartTimer (new TimeSpan (0, 0, 60), () => {
// do something every 60 seconds
return true; // runs again, or false to stop
});
If you want to start and stop the timer via buttons, you could do something like this:
bool timerStatus = false;
btnStart.Clicked += delegate {
timerStatus = true;
Device.StartTimer (new TimeSpan(h,m,x), () => {
if (timerStatus) {
// do work
}
return timerStatus;
});
};
btnStop.Clicked += delegate {
timerStatus = false;
};
Xamarin Forms libraries are Portable class libraries and as such, Timers are not part of the API for certain target platform combinations.
A good implementation replacement for a time would be an implementation using Task.Delay
, marked as internal to avoid issues when using the PCL library on a platform that has timers available. You can use this code as a drop-in shim (source: link above):
internal delegate void TimerCallback(object state);
internal sealed class Timer : CancellationTokenSource, IDisposable
{
internal Timer(TimerCallback callback, object state, int dueTime, int period)
{
Contract.Assert(period == -1, "This stub implementation only supports dueTime.");
Task.Delay(dueTime, Token).ContinueWith((t, s) =>
{
var tuple = (Tuple<TimerCallback, object>)s;
tuple.Item1(tuple.Item2);
}, Tuple.Create(callback, state), CancellationToken.None,
TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.Default);
}
public new void Dispose() { base.Cancel(); }
}
来源:https://stackoverflow.com/questions/30399796/xamarin-forms-error-using-system-timers-and-sysem-json