【问题标题】:Running two background tasks in xamarin forms以 xamarin 形式运行两个后台任务
【发布时间】:2018-01-11 13:14:02
【问题描述】:

我想在我的 xamarin 表单移动应用上运行两个后台线程。

问题是我希望以不同的频率调用这些任务。

打电话给一个,我这样做了:

 protected  override void OnStart()
    {
        // Handle when your app starts
        // On start runs when your application launches from a closed state, 
        if (!stopWatch.IsRunning)
        {
            stopWatch.Start();
        }

        Device.StartTimer(new TimeSpan(0, 0, 1), () =>
       {
           if (stopWatch.IsRunning && stopWatch.Elapsed.Seconds == 20) //first task
           {
               MyMethod(this).ContinueWith((Task t) =>
                {
                    stopWatch.Restart();
                       return true;
                });
           }


         //second method?



           //  Always return true as to keep our device timer running, false if we want to cancel the timer.
           return true;
        });
    }

那段代码运行良好。问题是我想以不同的频率调用第二个任务。我应该把它放在哪里?

【问题讨论】:

  • 就在第一个下面?只需从Device.StartTimer 开始复制和粘贴,然后创建一个stopWatch2 变量。
  • @hvaughan3 ,它不起作用。第一个任务(方法)总是被调用,因为它的调用频率低于每 50 秒调用一次的第二个方法。第二种方法永远不会被调用。

标签: c# xamarin concurrency xamarin.forms task


【解决方案1】:

我只会使用一个 Timer 使用一个对它们都有效的时间间隔,并使用一个计数器来查看触发哪个。

例如,如果您有 1 个任务要在 20 秒时运行,而另一个任务要在 30 秒时运行。将间隔设置为 10 秒。使用类级别变量来保存计数并在第二个任务之后将其重置。

        intervalCount++;
        if(intervalCount == 2)
        {
            // Do function 1
        }
        else if(intervalCount == 3)
        {
            // Do function 2 and reset our counter
            intervalCount == 0;
        }

【讨论】:

  • 这也不起作用。函数 2 永远不会被调用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 2019-11-16
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多