【问题标题】:Good way to make Userdialog.Instance.Progress wait for method to execute C# Xamarin使 Userdialog.Instance.Progress 等待方法执行 C# Xamarin 的好方法
【发布时间】:2022-02-10 23:01:54
【问题描述】:

我正在尝试显示一个进度对话框,显示使用等待所有内容的方法完成的百分比 + await Task.Delay(20); 和等待我要执行的方法。现在我注意到使用 task.delay 执行需要更长的时间。

我想要实现的是 progress.dialog 计算该方法需要多长时间而不是延迟它,因为它的工作速度要慢一些。

我有哪些选择?

这是我的代码

    private async Task DownloadAllAlert()
    {
        //alert to download everything
        bool result = await DisplayAlert("Download", "Do you want to download everything?", "Yes", "No"); ;

        //alert is user chose yes
        if (result)
        {
            // loading dialog in percentage till downloading is done
            using (var progress = UserDialogs.Instance.Progress("Loading..."))
            {
                for (var i = 0; i < 100; i++)
                {
                    progress.PercentComplete = i;
                    await Api.DownloadAll();
                    await Task.Delay(20);
                }
            }
        }
    }

【问题讨论】:

  • 您拨打Api.DownloadAll() 100 次 - 您确定这是您想要做的吗?另外:Now I notice that with that task.delay the execution takes much longer. - 这就是 Task.Delay 的设计目的。
  • 哦,我的错,但如果我将其设置为 1,则对话框在方法结束之前结束@FranzGleichmann

标签: c# xamarin async-await android-asynctask mvvmcross


【解决方案1】:

尝试在 c# 中使用 Task。

using (var progress = UserDialogs.Instance.Progress("Loading..."))
{
    await LoadData(ref progress);
}

调用这个函数

public async Task LoadData(ref IProgressDialog progress);
{
  //await Task.Yield(); //add this line of code if on ios didnt work
  
 Task task1 = new Task(() =>
    {
        for (int i = 0; i < 50 ; i++) // loop untill 50% then increase sleeping thread time
        {
            progress.PercentComplete = i;     
            //sleeping for 1 second  
            Thread.Sleep(1000);
        }
        for (int i = 50; i < 100; i++) // loop untill 99% then stop
        {
            progress.PercentComplete = i;     
            //sleeping for 2 second  
            Thread.Sleep(2000);
        }
        Console.WriteLine("Task 1 complete");
    });

    Task task2 = new Task(() =>
    {
        await Api.DownloadAll();
        Console.WriteLine("Task 2 complete");
    });

    //starting the tasks  
    task1.Start();
    task2.Start();
    Task.WaitAny(task2);
    progress.PercentComplete = 100; // when task2 finish put it 100%
}

【讨论】:

  • 那么我的using (var progress = UserDialogs.Instance.Progress("Loading...")) 应该放在哪里? @Amjad S.
  • 使用 (var progress = UserDialogs.Instance.Progress("Loading...")) 将我的代码放入其中
  • 它对你有用吗?
  • no 那么加载对话框不再弹出
  • 你会用 UserDialogs.Instance.ShowLoading 替换它吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 2020-12-07
  • 1970-01-01
  • 2022-01-27
  • 2022-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多