2011-04-27 59 views
3

在我的应用程序中,我需要一个关闭计时器,它将执行一个动作并永不再使用。最近我一直在镇压性能,并且想知道正确的做法是什么。在Monotouch中正确处理NSTimer

如果我做到以下几点:

NSTimer.CreateScheduledTimer(10, delegate { 
    Console.WriteLine("Timer fired!"); 
    // other non-trivial code here 
}); 

一旦这已经解雇,这是怎么回事通过Mono的GC可以自动的清理?或者最好是创建一个对这个定时器的引用(NSTimer timer = NSTimer.CreateScheduledTimer()),然后自己处理它?

这是否适用于可以类似方式实例化的其他对象?

回答

3

您的示例代码可能是要走的路。定时器启动后,GC会清理一段时间。你可能想要保持对定时器的引用的唯一原因是如果你想在某个时候取消定时器。

1

我使用这个小帮手。好的一点是,它可以用在所有的NSObject派生类中,并且在转换来自ObjC的代码时有所帮助,因为它几乎是相同的调用。

namespace MonoTouch.Foundation.Extensions 
{ 
    public static class CoreFoundationExtensions 
    { 
     /// <summary> 
     /// Performs the selector. 
     /// </summary> 
     /// <param name='obj'> 
     /// Object. 
     /// </param> 
     /// <param name='action'> 
     /// Action. 
     /// </param> 
     /// <param name='delay'> 
     /// Delay. 
     /// </param> 
     public static void PerformSelector (this NSObject obj, NSAction action, float delay) 
     { 
      int d = (int)(1000 * delay); 

      var thread = new Thread(new ThreadStart (() => { 
       using(var pool = new NSAutoreleasePool()) 
        { 
         Thread.Sleep (d); 
         action.Invoke(); 
        } 
      }));   

      thread.IsBackground = true; 
      thread.Start(); 
     } 

     /// <summary> 
     /// Performs the selector. 
     /// </summary> 
     /// <param name='obj'> 
     /// Object. 
     /// </param> 
     /// <param name='action'> 
     /// Action. 
     /// </param> 
     public static void PerformSelector (this NSObject obj, NSAction action) 
     { 
      PerformSelector (obj, action, 0.001f); 
     } 
    } 
}