我正在使用 Task.FromAsync 和 Task.ContinueWith 方法来完成我的工作。我在我的程序中使用一个列表,当我运行它时,它给了我一个索引超出范围异常。但是,当我通过调试器时,它会运行并完成得很好。将它们与循环和列表一起使用时,是否有我遗漏的东西或者任务的操作方式不同?
public int TimerCounter = 0;
public IList<WebsiteResult>webResult = new List<WebsiteResult>();
public void sendRequest(){
foreach(Website web in TempVar._allWebsites)
{
webResult.Add(new WebSiteResult {});
try
{
pageCheck(web);
webResult.ElementAt(TimerCounter).RequestSentTime = DateTime.Now.ToString();
if(webResult.ElementAt(TimerCounter).SystemStatus == null)
webResult.ElementAt(TimerCounter).SystemStatus = "";
TimeCounter++;
}
}
public void pageCheck(){
IAsyncResult asyncResult;
Uri uri = new Uri(TempURL); //TempUrl is assigned a string beforehand
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(uri);
try{
Task<WebResponse> task = Task.Factory.FromAsync(
myReq.BeginGetResponse,
asyncResult => myReq.EndGetResponse(asyncResult),
(Object)null);
task.ContinueWith(t =>
{
var responseCode = (HttpWebResponse)t.Result;
ReadStreamFromResponse(t.Result);
if(responseCode.StatusCode == HttpStatusCode.OK){
webResult.ElementAt(TimerCounter).ResponseStatusCode = "Up"; //Error occurs here
reponseCode.Close();
}
}
);
}
//catch exceptions
}
private String ReadStreamFromResponse(WebResponse response) {
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string str = responseStream.ReadToEnd();
return str;
}