繁体   English   中英

如何在Xamarin.Forms中实现异步计时器

[英]How to implement an async timer in Xamarin.Forms

我正在Xamarin.Forms中实现录音机。 应该有一个计时器,显示记录器的运行时间。 点击图像时,记录开始,如果用户再次点击,记录将停止。 点击的命令代码如下:

    /// <summary>
    ///     The on tabbed command.
    /// </summary>
    private async void OnTappedCommand()
    {
        if (this.isRecording)
        {
            this.isRecording = false;
            await this.StopRecording().ConfigureAwait(false); // Stops the MediaRecorder
        }
        else
        {
            this.isRecording = true;
            await this.StartTimer().ConfigureAwait(false); // Starts the Timer
            await this.StartRecording().ConfigureAwait(false); // Starts the MediaRecorder
        }
    }

StartTimer()方法如下所示:

private async Task StartTimer()
    {
        Device.StartTimer(
            new TimeSpan(0, 0, 0, 0, 1),
            () =>
                {
                    if (this.isRecording)
                    {
                        Device.BeginInvokeOnMainThread(
                            () =>
                                {
                                    this.TimerValue = this.TimerValue + 1;
                                });

                        return true;
                    }

                    Device.BeginInvokeOnMainThread(
                        () =>
                            {
                                this.TimerValue = 0;
                            });

                    return false;
                });
}

TimerValue是绑定到使用ValueConverter处理格式的标签的简单整数属性。

我的问题是:

1.即使删除了Device.BeginInvokeOnMainThread方法,为什么我的代码也可以工作? 由于使用了ConfigureAwait(false),它是否不在UI-Thread上运行并尝试更新UI-Bound TimerValue属性,是否应该引发错误?

2.您在此代码中建议在哪里使用Task.Run(),或者根本不应该使用它?

1-之所以起作用,是因为计时器将在UI线程 (主线程)中运行代码。 与Device.BeginInvokeOnMainThread()使用的相同。 您可以在代码用完UI线程时使用它(请参阅下一个答案)

2-在您的示例中根本不应该使用它,因为this.TimerValue是由UI线程 Task.Run()创建的(并且是其属性),它在“线程池”中执行代码,并且无法触摸由创建的对象“ UI线程”。 “线程池”将用于较长的作业,并且不应与UI交互。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM