GetResponse()花了太长时间

时间:2011-11-14 20:05:04

标签: c# winforms multithreading asynchronous

我正在开发winforms应用程序。

我有一个验证网址的功能。

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

此代码工作正常,我得到了正确的值,但是处理此问题并且大多数情况下应用程序被挂起都需要很长时间。

我是线程新手,所以有没有办法实现它。 一个例子真的很有帮助

如果还有其他更好的方法,请告诉我。

由于

3 个答案:

答案 0 :(得分:2)

查看BackgroundWorker控件。这是一种简单的方法。

HTH。

答案 1 :(得分:1)

当您自己指出解决方案时,必须异步执行提取。 BackgroundWorker是一个很好的开始,特别是因为它是一个原生的WinForms组件。

如果您想以更一般的方式解决它,您还可以在C#中查看新的async扩展名。

答案 2 :(得分:1)

执行此操作的一个好方法是使用线程池:

实施起来很简单,并且可以很好地处理大量请求。

您还可以指定最大线程数和循环来执行15,25,50等的集合,这样您就不会剪切太多线程并最终削减更多线程然后有一个好处。我会玩它来找出你何时开始放松优化。

好处是(通过第一个链接)传递一个对象(Object threadContext),其中不必是单个值...它可以是一个数组,一个列表等,它被转换为一个宾语。使用列表等时,您可能需要查看一下线程安全性=,但我觉得这可能比您在此时使用线程更多。

如果有帮助,请评价。

相关问题