我使用xamarin表单,我需要使用这个程序集(使用System.Timers;)但是当我现在写它时它找不到Timers。我需要添加包吗?
我想这样用:
var timer = new Timer (1000);
timer.Elapsed += OnTimerElapsed;
timer.Start ();
public static void OnTimerElapsed(object o, ElapsedEventArgs e)
{
//code
}
答案 0 :(得分:4)
您想在PCL项目中使用Timer类吗?如果是这样,您将不得不使用Device.StartTimer
Device.StartTimer (new TimeSpan (0, 0, 60), () => {
// do something every 60 seconds
return true; // runs again, or false to stop
});
答案 1 :(得分:0)
System.Timers来自System.dll程序集。 以下是来自msdn
的信息答案 2 :(得分:0)
根据PCL配置文件,Timer类不可用。我使用这段代码代替:
delegate void TimerCallback(object state);
sealed class Timer : CancellationTokenSource, IDisposable
{
internal Timer(TimerCallback callback, object state, int dueTime, int period)
{
if (dueTime <= 0)
throw new ArgumentOutOfRangeException("dueTime", "Must be positive integer");
if (period <= 0)
throw new ArgumentOutOfRangeException("period", "Must be positive integer");
Task.Delay(dueTime, Token).ContinueWith(async (t, s) =>
{
var tuple = (Tuple<TimerCallback, object>)s;
while (true)
{
if (IsCancellationRequested)
break;
Task.Run(() => tuple.Item1(tuple.Item2));
await Task.Delay(period);
}
}, Tuple.Create(callback, state), CancellationToken.None,
TaskContinuationOptions.OnlyOnRanToCompletion,
TaskScheduler.Default);
}
public new void Dispose()
{
Cancel();
}
}