Xamarin C#如何使用取消令牌停止进度栏过程?

时间:2019-12-28 20:36:08

标签: c# .net multithreading xamarin

该应用会录制声音。当用户按下“停止录制”但进度条当前未停止时,我试图停止进度条。这是我尝试过的:

private async Task RecordAudio()
        {
            buttonSave.IsEnabled = false;
            CancellationTokenSource cts = new CancellationTokenSource();

            try
            {
                if (!recorder.IsRecording)
                {
                    buttonRecord.IsEnabled = false;
                    buttonPlay.IsEnabled = false;

                    // only if ios
                    if (Device.RuntimePlatform == Device.iOS)
                        DependencyService.Get<IAudioService>().PrepareRecording();


                    var recordTask = await recorder.StartRecording();

                    RunProgressActivity(cts.Token);

                    buttonRecord.Text = "Stop";
                    buttonRecord.IsEnabled = true;

                    // get the recorded file
                    var recordedAudioFile = await recordTask;


                    if (recordedAudioFile != null)
                    {
                        // do something with it
                        buttonSave.IsEnabled = true;
                    }

                    buttonRecord.Text = "Record";
                    buttonPlay.IsEnabled = true;
                }
                else // stop button clicked
                {
                    cts.Cancel(); // here is where i am trying to stop the progress bar

                    buttonRecord.IsEnabled = false;

                    await recorder.StopRecording();

                    buttonSave.IsEnabled = true;                 
                    buttonRecord.IsEnabled = true;
                }
            }
            catch (OperationCanceledException)
            {

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            cts = null;
        }

方法和进度条的方法:

private async void RunProgressActivity(CancellationToken cancelToken) => await progressBarRecordTime.ProgressTo(1, 20000, Easing.Linear);

我知道我缺少了什么,能请您指出正确的方向吗?

1 个答案:

答案 0 :(得分:1)

根据您的描述,CancelationToken可能用于在后台下载长文件或其他操作,您想停止Progressbar,我认为它将出现一些问题。 这是有关使用CancellationToken的文章:

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks

我建议您可以遵循Bijington的意见,这样做:

 private async void Start_Clicked(object sender, EventArgs e)
    {
        //do other operation
        progressbar1.Animate("SetProgress", (arg) => { progressbar1.Progress = arg; }, 8 * 60, 8 * 1000, Easing.Linear);

    }

    private void Stop_Clicked(object sender, EventArgs e)
    {
        if (progressbar1.AnimationIsRunning("SetProgress"))
        {
            progressbar1.AbortAnimation("SetProgress");
        }
    }

如果我的回复对您有帮助,请记住将我的回复标记为答案,谢谢。