Xamarin使用System.Timers和Sysem.Json形成错误

Use*_*382 1 xamarin.ios xamarin xamarin-forms

我想在我的基于Xamarin Forms的项目中使用System.Timer.我实际上将我的Xamarin iOS项目转换为Xamarin Formbased项目.我的Xamarin iOS项目包含使用System.Timer的Timer的所有代码

  aTimer = new Timer (tm);

  // Hook up the Elapsed event for the timer.
  aTimer.Elapsed += new ElapsedEventHandler (OnTimedEvent);


  aTimer.Enabled = true;
  aTimer.Start ();
Run Code Online (Sandbox Code Playgroud)

当我尝试在Xamarin Forms项目中使用相同的代码时,它给出了错误.首先

using System.Timers;
Run Code Online (Sandbox Code Playgroud)

它说:命名空间System中不存在类型或命名空间名称Timers.你错过了装配参考吗?

Xamarin iOS系统是否与Xamarin Forms System参考不同?

Jas*_*son 7

PCL项目不支持System.Timer.

Xamarin Forms有一个内置的计时器来帮助解决这个限制

Device.StartTimer (new TimeSpan (0, 0, 60), () => {
    // do something every 60 seconds
    return true; // runs again, or false to stop
});
Run Code Online (Sandbox Code Playgroud)

如果你想通过按钮启动和停止计时器,你可以这样做:

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;
};
Run Code Online (Sandbox Code Playgroud)