Search code examples
c#winformsmultithreadingasynchronous

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


Solution

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