shadyamigo
shadyamigo

Reputation: 25

Cancel webclient Async request

Hopefully an easy question for you all but I'm really struggling. I've only recently started programming and have just had an app certified to the WP7 app store but noticed a bug myself that i would like to fix before making the app public.

Basically I have a search box where the user enters a chemical name and a webservice returns an image and its molecular weight. What i would like to do is cancel the webclient if the user navigates away from the page before the download is completed or if a new search is made before the previous is completed (this currently crashes the app as I believe you can only have one request at a time??)

private void searchCactus()
        {

            WebClient imgClient = new WebClient();
            imgClient.OpenReadCompleted += new OpenReadCompletedEventHandler(imgClient_OpenReadCompleted);

            WebClient mwClient = new WebClient();
            mwClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(mwClient_DownloadStringCompleted);

           if (DeviceNetworkInformation.IsNetworkAvailable == false)
            {
                MessageBox.Show("No network found, please check network availability and try again");
            }
            else if (compoundSearchBox.Text.Contains("?"))
                {
                    MessageBox.Show("\"?\" Not Permitted");
                    return;
                }
            else if (compoundSearchBox.Text != "")

                {

                    progBar1.IsIndeterminate = true;

                    string imageuri = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/image?format=png&width=300&height=300";
                    string mwURI = "http://cactus.nci.nih.gov/chemical/structure/" + compoundSearchBox.Text + "/mw";

                    imgClient.OpenReadAsync(new Uri(@imageuri), imgClient);



                 mwClient.DownloadStringAsync(new Uri(@mwURI), mwClient);

 // //lower keyboard   
                this.Focus();

                }
                else MessageBox.Show("Enter Search Query");

        }

I tried implementing the following button but it does not work

private void buttonCancel_Click(object sender, RoutedEventArgs e)
    {
        imgClient.CancelAsync();
        mwClient.CancelAsync();
    }

as "the name 'mwClient' does not exist in the current context"

I would be very grateful if anybody could provide some guidance

Upvotes: 1

Views: 2077

Answers (1)

svick
svick

Reputation: 244767

Just put the two clients into fields in your class.

Upvotes: 2

Related Questions