取消WebClient DownloadTask异步

时间:2017-07-03 12:55:14

标签: c# xamarin xamarin.android webclient cancellation

我有一个用于下载文件的WebClient 这是我的代码,我有一个ProgressDialog和一个WebClient可供下载:

dialog = new ProgressDialog(mContext);
                dialog.SetProgressStyle(Android.App.ProgressDialogStyle.Horizontal);
                dialog.SetCancelable(true);
                dialog.SetCanceledOnTouchOutside(true);

                dialog.Show();// showing a dialog

                string url = "myurl";

                WebClient webClient = new WebClient();
                webClient.DownloadProgressChanged += WebClient_DownloadProgressChanged;
                dialog.CancelEvent += (s, e) =>
                {
                    webClient.CancelAsync();
       //----------------------- Crashes Here
                };

                try
                {
                    bytes = await webClient.DownloadDataTaskAsync(url);
                }
                catch (TaskCanceledException)
                {
                    return;
                }
                catch (Exception a)
                {
                    return;
                }

如何在中间取消下载?

webClient.CancelAsync();

抛出异常:

Object reference not set to an instance of an object

1 个答案:

答案 0 :(得分:2)

当内部异常为null时,问题出现在异常处理代码中。使用"?"

来检查内部异常
dialog.CancelEvent += (s, e) =>
                    {
                        webClient.CancelAsync();
                    };

                    try
                    {
                        bytes = await webClient.DownloadDataTaskAsync(url);
                    }
                    catch (WebException wex)
                    {
                        if (wex.Status == WebExceptionStatus.RequestCanceled)
                            return;
                        Toast.MakeText(mContext, wex.Message + "," + wex?.InnerException?.Message, ToastLength.Long).Show();
                        dialog.Progress = 0;
                        return;
                    }
                    catch (TaskCanceledException)
                    {
                        return;
                    }
                    catch (Exception a)
                    {
                        Toast.MakeText(mContext, a.Message + "," + a?.InnerException?.Message, ToastLength.Long).Show();
                        dialog.Progress = 0;
                        return;
                    }