2011-03-29 44 views
2

我遇到了一個問題,那就是在發佈模式下編譯時,我的設備上的大部分時間(而非全部)我的NSTimer操作未被調用。在設備上的調試模式下總是很好,在模擬器的任何一種模式下總是很好。設備上的發佈模式中的間歇性NSTimer問題

對這種情況唯一有點不尋常的是,它被另一個類包裹起來,允許我們在運行時注入特定於平臺的實現,例如定時器,思考向monodroid等等。儘管如此,沒有什麼特別的異常。

代碼:

using System; 
using MonoTouch.Foundation; 
namespace OurCompany.PlatformAbstraction.Ios 
{ 
    public class IosTimer : IPlatformTimer 
    { 
    private NSTimer backingTimer; 
    public double IntervalMs{get; set;} 

    public IosTimer(double intervalMS) 
    { 
     this.IntervalMs = intervalMS; 
    } 

    public event EventHandler Elapsed; 

    private void NsTimerElapsed() 
    { 
     if (Elapsed != null) 
     { 
      Elapsed(this, EventArgs.Empty); 
     } 
    } 

    public void Start() 
    { 
     TimeSpan ts = TimeSpan.FromMilliseconds(this.IntervalMs); 
     this.backingTimer = NSTimer.CreateRepeatingScheduledTimer(ts, NsTimerElapsed); 
    } 

    public void Stop() 
    { 
     this.backingTimer.Invalidate(); 
     this.backingTimer = null; 
    } 
    } 
} 

調用代碼:

private IosTimer t; 

public override void ViewDidLoad() 
{ 
    base.ViewDidLoad(); 

    t = new IosTimer(100); 
    t.Elapsed += UpdateLabel; 
    t.Start(); 
} 

private void UpdateLabel(object sender, EventArgs e) 
{ 
    // not being called in Release mode on the phone 
    // works fine in Debug mode on the phone, works fine in both modes in the simulator 
} 

我也注意到一般行爲的差異 - 在一些正常工作在模擬器,但無法在設備上。由於兩個完全相同的代碼部署到同一個設備(!),所以也有輕微的行爲變化

昨天發佈在MonoTouch論壇上,但它在那裏似乎有點安靜。

在此先感謝。

+0

請在http://monotouch.net/Support – 2011-03-29 15:39:45

+0

上提供一個測試用例的錯誤您是否嘗試過使用System.Timers.Timer?我已經使用它,並沒有像你提到的任何問題。 – jonathanpeppers 2011-03-29 23:43:45

+0

啊,輝煌 - 出於某種原因,我的印象是System.Timers.Timer在MonoTouch可用的庫中不存在。更少的東西要抽象... – tomfanning 2011-03-30 09:56:23

回答

0

發生這是線程相關。通過在我的Elapsed事件處理程序中使用InvokeOnMainThread()來解決。