我正在使用winforms應用程序。GetResponse()花費太長
我有一個函數來驗證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);
}
}
}
}
此代碼工作正常,我也得到了正確的價值觀,但它正在採取長時間來處理這和大多數應用程序被絞死的時代。
我是新線程,所以有辦法實現它。 一個例子將會非常有用
如果還有其他更好的方法可以做到這一點,請告訴我。
感謝
這是偉大的...但我有一些麻煩實施它..你可以請幫助我。像我如何調用背景功能。你能告訴我一個樣本或東西 – user175084
看看這個例子:http://msdn.microsoft.com/en-us/library/hybbz6ke.aspx –
本質上,該控件在另一個線程中運行該操作。主要處理DoWork事件,最後將Web請求的結果傳遞給e.Result屬性。您不能直接將它返回給表單,而是必須通過e.Result返回。然後,在表單中,您可以通過此事件arg訪問結果,並執行您最初所需的任何操作。 –