我正在使用.Net 4.5.1构建一个针对IOS Android和Windows Phone 8.1的Xamarin跨平台应用。当我尝试在PCL项目中引用System.Timers时,它不存在。我该如何解决这个问题?
答案 0 :(得分:11)
您可以使用:Device.StartTimer
语法:
public static void StartTimer (TimeSpan interval, Func<bool> callback)
示例:每1秒递增一次,持续1分钟
int number = 0;
Device.StartTimer(TimeSpan.FromSeconds(1),() => {
number++;
if(number <= 60)
{
return true; //continue
}
return false ; //not continue
});
示例:等待5秒钟运行一次功能
Device.StartTimer(TimeSpan.FromSeconds(5),() => {
DoSomething();
return false ; //not continue
});
答案 1 :(得分:5)
前几天我注意到了这一点。虽然这个类在API文档System.Threading.Timer Class中,但是很烦人。
无论如何,我使用Task.Delay()
创建了自己的Timer类:
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;
}
}