简体   繁体   中英

GetResponse() taking too long

I am working on a winforms application.

I have a function to validate the URL.

  private void checkForSPSiteValidity(DataGridView Sites_dataGridView)
    {
        foreach (DataGridViewRow myRow in SharePointSites_dataGridView.Rows)
        {
            try
            {
                DataGridViewImageCell cell = myRow.Cells[CommonCodeClass.status_GridCol] as DataGridViewImageCell;

                string url = myRow.Cells[CommonCodeClass.spURL_GridCol].Value.ToString();

                WebRequest req = WebRequest.Create(url);

                WebResponse res = req.GetResponse();

                cell.Value = Image.FromFile(CommonCodeClass.Correct_Icons);

            }
            catch (WebException ex)
            {
                Console.WriteLine(ex.Message);
                if (ex.Message.Contains("remote name could not be resolved"))
                {
                    DataGridViewImageCell cell = myRow.Cells[CommonCodeClass.status_GridCol] as DataGridViewImageCell;

                    cell.Value = Image.FromFile(CommonCodeClass.warning_Icon);
                }
            }
        }
    }

This code is working fine and i get the correct values but it is taking to long to process this and most of the times the application gets hanged.

I am new to threading so is there a way to implement it with that. An example will be really helpful

If there is any other better way to do this please let me know.

Thanks

Check out the BackgroundWorker control. That's one simple way to do it.

HTH.

As you point out to solution yourself, you must perform the fetch asynchronously. BackgroundWorker is a good class to start, especially because it is a native WinForms component.

You can also look into new coming async extensions in C# if you want to solve it in a more general way.

A great way to do this is using a Thread Pool:

It's simple to implement and would be great at crunching a high volume of requests.

You can also specify a max number of threads and loop to do sets of 15, 25, 50, etc so you don't cut too many threads and end up cutting more threads then there is a benefit. I would play around with it to find out when you start to loose optimization.

The nice thing is that (see first link) you pass an object (Object threadContext) where this doesn't have to be a single value... it can be an array, a list, etc that is cast as an object. When working with lists, etc you may have to look up a bit on thread safety=, but I feel this is probably more then you are doing with threading at this point.

.

.

Please rate if helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM