【问题标题】:Stop the System.Timers in C#在 C# 中停止 System.Timers
【发布时间】:2021-02-09 19:34:28
【问题描述】:

我正在使用 System.Timers 并且计时器正在完美地工作,例如在Second 4, 8, 12, 16 上拍照。

但是,我希望它在 Second 17 上导航,但它不会。

代码

public partial class CustomCameraPage : ContentPage
{
    private static Timer timer_click;
    int Seconds = 0;

    public CustomCameraPage()
    {
        timer_click = new Timer();
        timer_click.Interval = 1000;
        timer_click.Elapsed += OnTimedEvent;
        timer_click.Enabled = true;
        timer_click.AutoReset = true;
        timer_click.Start();

        InitializeComponent();
    }
        
    public void OnTimedEvent(object source, ElapsedEventArgs e)
    {
        Seconds++;

        if (Seconds == 4 || Seconds == 8 || Seconds == 12 || Seconds == 16) MessagingCenter.Send<object>(this, "A");
        if (Seconds == 17) Navigation.PushModalAsync(new FormPage());
    }   
}

【问题讨论】:

  • 所以什么都没有发生?还是抛出异常究竟发生了什么?
  • 旁注:您假设计时器的时间间隔是准确的,这充其量是幼稚的。您的Seconds 变量不是自计时器启动以来经过的秒数的准确表示,而是OnTimedEvent 方法被调用次数的准确表示。
  • 还有一些吹毛求疵:if (Seconds == 4 || Seconds == 8 || Seconds == 12 || Seconds == 16) 可以简化为 if(Seconds &lt; 17 &amp;&amp; Seconds % 4 == 0) 但这真的只是吹毛求疵...
  • 在计时器上调用 Stop(),并使用 Xamarin Essentials 中的 MainThread 执行导航
  • 您是否允许从与拥有内容页面的线程不同的线程推送导航?我不熟悉 Xamarin.Forms 在这方面的工作方式。

标签: c# .net xamarin .net-core xamarin.forms


【解决方案1】:

MainThread上执行导航

if (Seconds == 17) 
{
  timer_click.Stop();
  MainThread.BeginInvokeOnMainThread(() =>
  {
    Navigation.PushModalAsync(new FormPage());
  });
}

【讨论】:

  • 谢谢,它工作了 :) 但为什么它卡住了 1-2 秒然后它导航了?
猜你喜欢
  • 2012-05-26
  • 1970-01-01
  • 2014-11-19
  • 1970-01-01
  • 1970-01-01
  • 2019-07-03
  • 2014-09-23
  • 2013-12-07
  • 1970-01-01
相关资源
最近更新 更多