c# - 停止/退出定时器

标签 c# xamarin

我正在尝试在 5 秒后退出下面的计时器。

我尝试了 workoutTimer.Stop();,但得到的消息是“workoutTimer”在上下文中不存在。

非常感谢任何反馈。

var i = 0;
var workoutTimer = new Timer((o) => {
    Device.BeginInvokeOnMainThread(() => {
        i = i+1;
        if (if i == 5){
            Console.WriteLine('Exit Timer here');
            //workoutTimer.Stop();
        }
    });
}, null, 1000, 1000);

最佳答案

您是否尝试过调用 Dispose() 并创建一个私有(private) Timer 变量,如下所示:

Timer workoutTimer;
void TimerMethod () {
    var i = 0;
    workoutTimer = new Timer (o =>  {Device.BeginInvokeOnMainThread (() =>  {
        i = i + 1;
        if (i == 5) {
            Console.WriteLine ("Exit Timer here");
            workoutTimer.Dispose ();
        }
        Console.WriteLine ("tick");
    });
    }, null, 1000, 1000);
}

关于c# - 停止/退出定时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31126549/

相关文章:

C# 十进制转 SQL Server Money

xamarin - 在 Xamarin MVVM 中单击按钮更改标签值

java - Java 加密与 And .NET 的十六进制生成问题

c# - X = X++; 有什么区别?与 X++;?

android - Xamarin with Visual Studio : Resource. Id 不包含 "..."的定义

c# - 使按钮打开超链接

Azure 移动服务错误 --- 请求无法完成。 ()

xamarin - UWP : Payload contains two or more files with the same destination path

c# - System.Reflection - 如何调用子级别类型的 getter 方法?

c# - 使用 MahApp.Metro 主题自定义 SaveFileDialog