Sep*_*ani 6 .net c# cross-platform xamarin
我正在使用.Net 4.5.1构建一个针对IOS Android和Windows Phone 8.1的Xamarin跨平台应用程序.当我尝试在PCL项目中引用System.Timers时,它不存在.我该如何解决?
小智 11
您可以使用:Device.StartTimer
句法 :
public static void StartTimer (TimeSpan interval, Func<bool> callback)
Run Code Online (Sandbox Code Playgroud)
示例:每1秒递增1分钟
int number = 0;
Device.StartTimer(TimeSpan.FromSeconds(1),() => {
number++;
if(number <= 60)
{
return true; //continue
}
return false ; //not continue
});
Run Code Online (Sandbox Code Playgroud)
示例:等待5秒钟以运行一次功能
Device.StartTimer(TimeSpan.FromSeconds(5),() => {
DoSomething();
return false ; //not continue
});
Run Code Online (Sandbox Code Playgroud)
前几天我注意到了这一点.虽然这个类是在API文档System.Threading.Timer Class ..Annoying.
无论如何,我创建了自己的Timer类,使用Task.Delay():
public class Timer
{
private int _waitTime;
public int WaitTime
{
get { return _waitTime; }
set { _waitTime = value; }
}
private bool _isRunning;
public bool IsRunning
{
get { return _isRunning; }
set { _isRunning = value; }
}
public event EventHandler Elapsed;
protected virtual void OnTimerElapsed()
{
if (Elapsed != null)
{
Elapsed(this, new EventArgs());
}
}
public Timer(int waitTime)
{
WaitTime = waitTime;
}
public async Task Start()
{
int seconds = 0;
IsRunning = true;
while (IsRunning)
{
if (seconds != 0 && seconds % WaitTime == 0)
{
OnTimerElapsed();
}
await Task.Delay(1000);
seconds++;
}
}
public void Stop()
{
IsRunning = false;
}
}
Run Code Online (Sandbox Code Playgroud)