2015-05-22 36 views
0

我想在我的基於Xamarin Forms的項目中使用System.Timer。我實際上將我的Xamarin iOS項目轉換爲Xamarin Formbased項目。我Xamarin的iOS項目有使用System.TimerXamarin使用System.Timers和Sysem.Json形式錯誤

aTimer = new Timer (tm); 

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


    aTimer.Enabled = true; 
    aTimer.Start(); 

當我嘗試使用Xamarin形式相同的代碼工程中,給錯誤定時器所有代碼。首先

using System.Timers; 

它說:類型或命名空間名稱定時器不存在於命名空間系統中。您是否缺少裝配參考?

Xamarin iOS系統與Xamarin Forms系統參考不同嗎?

回答

6

PCL項目不支持System.Timer。

Xamarin形式有一個內置的Timer,以幫助解除此限制

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

如果要啓動和停止通過按鈕計時器,你可以做這樣的事情:

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; 
}; 
+0

我有兩個按鈕1 - 開始計時器和2 - 停止計時器。考慮到上面的代碼,我如何啓動和停止按鈕單擊計時器。在上面的代碼中,它具有分配新實例的新TimeSpan(0,0,60)。如何在STOP按鈕單擊時返回FALSE。 – User382

+0

看到我上面的編輯 – Jason

0

Xamarin Forms庫是可移植的類庫,因此定時器不是某些目標平臺組合的API的一部分。

A good implementation替換一段時間將是一個使用Task.Delay的實現,標記爲內部以避免在具有可用定時器的平臺上使用PCL庫時出現問題。您可以使用此代碼作爲嵌入式墊片(來源:上面的鏈接):

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(); } 
}