【问题标题】:Xamarin Forms Await/Async Task on Main ThreadXamarin 在主线程上形成等待/异步任务
【发布时间】:2020-07-20 10:30:38
【问题描述】:

我正在成功地将图像从我的应用程序下载到 iOS 和 android 的手机图库。以下是我的代码:

public void DownloadImages_Clicked(System.Object sender, System.EventArgs e)

        {

            CarDetailLoader.IsVisible = true;
            CarDetailLoader.IsRunning = true;

            foreach (var imgurl in car.CarImages)
            {
                var webClient = new WebClient();
                byte[] imageBytes = webClient.DownloadData(imgurl);

                DependencyService.Get<IMediaServices>().SaveImageFromByte(imageBytes, "DINImage");
            }

            CarDetailLoader.IsVisible = false;
            CarDetailLoader.IsRunning = false;
        }

但是,当此方法运行时,ActivityLoader 不起作用,即使它需要几秒钟。我尝试使用一些:

Task.Run(() => )

然而,我在网上阅读的方法,

“SaveImageFromByte()”方法只能在主线程上运行。

那么我该如何解决这个问题呢?

【问题讨论】:

  • 我的解决方案对您有用吗?如果是,请您接受(点击此答案左上角的☑️),以便我们可以帮助更多有相同问题的人:)。

标签: xamarin.forms async-await


【解决方案1】:

您可以使用Task.Run() 来等待任务并使用Device.BeginInvokeOnMainThread 在主线程中运行方法,这里是一个示例:

  public async void DownloadImages_Clicked()

    {
        Device.BeginInvokeOnMainThread(() => {
            CarDetailLoader.IsVisible = true;
            CarDetailLoader.IsRunning = true;
        });


        await Task.Run(async () =>
        {
            for (int i = 0; i< 3;i++)
            {

                //var webClient = new WebClient();
                //byte[] imageBytes = webClient.DownloadData((string)imgurl);
               
                Console.WriteLine("before delay");

                await Task.Delay(3000);

                Console.WriteLine("after delay");

                Device.BeginInvokeOnMainThread(() =>
                {
                    //DependencyService.Get<IMediaServices>().SaveImageFromByte(imageBytes, "DINImage");
                    Console.WriteLine("BeginInvokeOnMainThread");
                });         
            }
        });


        Device.BeginInvokeOnMainThread(() => {
            CarDetailLoader.IsVisible = false;
            CarDetailLoader.IsRunning = false;
        });

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-08
    • 2014-09-06
    • 1970-01-01
    相关资源
    最近更新 更多