Search code examples
c#xamarinxamarin.androidwebclientcancellation

Cancel WebClient DownloadTask Async


I have a WebClient which I use to download a file.
This is my code, in which I have a ProgressDialog and a WebClient to download:

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;
                }

How do I cancel the download in the middle?

webClient.CancelAsync();

throws an exception:

Object reference not set to an instance of an object

Solution

  • The problem was in exception handling code when inner exception was null. To make it work just checking for inner exception using "?"

    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;
                        }