C# 停止/退出计时器

C# 停止/退出计时器,c#,xamarin,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

我试图在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()
并创建如下的专用计时器变量:

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

如果您使用的是Xamarin.Forms,我建议使用而不是系统计时器。