using System.Windows.Forms;
using System.Net;
using System.IO;namespace DataGather
{
//异步下载类
public class MyHttpWebRequest
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout public static string ReadStr;
public static bool Suc;
public void MyDataGather(string ServerUrl,int i)
{
try
{
HttpWebRequest MyHttpWebRequest = (HttpWebRequest)WebRequest.Create(ServerUrl + i); // Create an instance of the RequestState and assign the previous myHttpWebRequest
// object to its request field.
RequestState MyRequestState = new RequestState();
MyRequestState.Request = MyHttpWebRequest; // Start the asynchronous request.
IAsyncResult Result =
(IAsyncResult)MyHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), MyRequestState); // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
ThreadPool.RegisterWaitForSingleObject(Result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), MyHttpWebRequest, DefaultTimeout, true); // The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne(); // Release the HttpWebResponse resource.
//此处在循环第二次出现 未将对象引用设置到对象实例 的异常
MyRequestState.Response.Close();
}
catch (WebException)
{
ReturnString("失败(一)!", false);
}
catch (Exception)
{
ReturnString("失败(二)!", false);
}
} private static void RespCallback(IAsyncResult AsynchronousResult)
{
try
{
// State of request is asynchronous.
RequestState MyRequestState = (RequestState)AsynchronousResult.AsyncState;
HttpWebRequest MyHttpWebRequest = MyRequestState.Request;
MyRequestState.Response = (HttpWebResponse)MyHttpWebRequest.EndGetResponse(AsynchronousResult); // Read the response into a Stream object.
Stream ResponseStream = MyRequestState.Response.GetResponseStream();
MyRequestState.StreamResponse = ResponseStream; // Begin the Reading of the contents of the HTML page and print it to the console.
IAsyncResult AsynchronousInputRead = ResponseStream.BeginRead(MyRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), MyRequestState);
return;
}
catch (WebException)
{
ReturnString("失败(三)!", false);
}
allDone.Set();
} private static void ReadCallBack(IAsyncResult AsyncResult)
{
try
{ RequestState MyRequestState = (RequestState)AsyncResult.AsyncState;
Stream ResponseStream = MyRequestState.StreamResponse;
int Read = ResponseStream.EndRead(AsyncResult);
// Read the HTML page and then print it to the console.
if (Read > 0)
{
//MyRequestState.RequestData.Append(Encoding.ASCII.GetString(MyRequestState.BufferRead, 0, Read));
MyRequestState.RequestData.Append(Encoding.GetEncoding("GB2312").GetString(MyRequestState.BufferRead, 0, Read));
IAsyncResult AsynchronousResult = ResponseStream.BeginRead(MyRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), MyRequestState);
return;
}
else
{
if (MyRequestState.RequestData.Length > 1)
{
string StringContent;
StringContent = MyRequestState.RequestData.ToString();
ReturnString(StringContent, true);
}
ResponseStream.Close();
allDone.Set();
}
}
catch (WebException)
{
ReturnString("失败(四)!", false);
}
} private static void TimeoutCallback(object State, bool TimedOut)
{
if (TimedOut)
{
HttpWebRequest Request = State as HttpWebRequest;
if (Request != null)
{
Request.Abort();
}
}
} public static void ReturnString(string TempStr,bool TempBool)
{
ReadStr = TempStr;
Suc = TempBool;
} }
public class RequestState
{
// This class stores the State of the request.
const int BUFFER_SIZE = 1024;
public StringBuilder RequestData;
public byte[] BufferRead;
public HttpWebRequest Request;
public HttpWebResponse Response;
public Stream StreamResponse;
public RequestState()
{
BufferRead = new byte[BUFFER_SIZE];
RequestData = new StringBuilder("");
Request = null;
StreamResponse = null;
}
} public class WebDataGather
{
private string ServerUrl = "http://web.com?id=" ;
public void StartGather()
{
for(int i=1;i<100;i++)
{
MyHttpWebRequest MyHttpWebRequest = new MyHttpWebRequest();
MyHttpWebRequest.MyDataGather(ServerUrl,i); string ReadStr = MyHttpWebRequest.ReadStr;
bool Suc = MyHttpWebRequest.Suc; if(Suc)
{
//输出ReadStr
}
} } }
}===================================================================大概就是这个样子的
但是 循环调用 异步下载的类 总会有问题//此处在循环第二次出现 未将对象引用设置到对象实例 的异常
MyRequestState.Response.Close();当把这里注释掉
执行没有问题 但是 后面字符串的输出会有问题 连续输出相同字符串 也就是循环调用的类执行时间长 而循环本身执行过快=========================================================
请朋友指明问题所在 并提出解决办法 谢谢
using System.Net;
using System.IO;namespace DataGather
{
//异步下载类
public class MyHttpWebRequest
{
public static ManualResetEvent allDone = new ManualResetEvent(false);
const int BUFFER_SIZE = 1024;
const int DefaultTimeout = 2 * 60 * 1000; // 2 minutes timeout public static string ReadStr;
public static bool Suc;
public void MyDataGather(string ServerUrl,int i)
{
try
{
HttpWebRequest MyHttpWebRequest = (HttpWebRequest)WebRequest.Create(ServerUrl + i); // Create an instance of the RequestState and assign the previous myHttpWebRequest
// object to its request field.
RequestState MyRequestState = new RequestState();
MyRequestState.Request = MyHttpWebRequest; // Start the asynchronous request.
IAsyncResult Result =
(IAsyncResult)MyHttpWebRequest.BeginGetResponse(new AsyncCallback(RespCallback), MyRequestState); // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted
ThreadPool.RegisterWaitForSingleObject(Result.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), MyHttpWebRequest, DefaultTimeout, true); // The response came in the allowed time. The work processing will happen in the
// callback function.
allDone.WaitOne(); // Release the HttpWebResponse resource.
//此处在循环第二次出现 未将对象引用设置到对象实例 的异常
MyRequestState.Response.Close();
}
catch (WebException)
{
ReturnString("失败(一)!", false);
}
catch (Exception)
{
ReturnString("失败(二)!", false);
}
} private static void RespCallback(IAsyncResult AsynchronousResult)
{
try
{
// State of request is asynchronous.
RequestState MyRequestState = (RequestState)AsynchronousResult.AsyncState;
HttpWebRequest MyHttpWebRequest = MyRequestState.Request;
MyRequestState.Response = (HttpWebResponse)MyHttpWebRequest.EndGetResponse(AsynchronousResult); // Read the response into a Stream object.
Stream ResponseStream = MyRequestState.Response.GetResponseStream();
MyRequestState.StreamResponse = ResponseStream; // Begin the Reading of the contents of the HTML page and print it to the console.
IAsyncResult AsynchronousInputRead = ResponseStream.BeginRead(MyRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), MyRequestState);
return;
}
catch (WebException)
{
ReturnString("失败(三)!", false);
}
allDone.Set();
} private static void ReadCallBack(IAsyncResult AsyncResult)
{
try
{ RequestState MyRequestState = (RequestState)AsyncResult.AsyncState;
Stream ResponseStream = MyRequestState.StreamResponse;
int Read = ResponseStream.EndRead(AsyncResult);
// Read the HTML page and then print it to the console.
if (Read > 0)
{
//MyRequestState.RequestData.Append(Encoding.ASCII.GetString(MyRequestState.BufferRead, 0, Read));
MyRequestState.RequestData.Append(Encoding.GetEncoding("GB2312").GetString(MyRequestState.BufferRead, 0, Read));
IAsyncResult AsynchronousResult = ResponseStream.BeginRead(MyRequestState.BufferRead, 0, BUFFER_SIZE, new AsyncCallback(ReadCallBack), MyRequestState);
return;
}
else
{
if (MyRequestState.RequestData.Length > 1)
{
string StringContent;
StringContent = MyRequestState.RequestData.ToString();
ReturnString(StringContent, true);
}
ResponseStream.Close();
allDone.Set();
}
}
catch (WebException)
{
ReturnString("失败(四)!", false);
}
} private static void TimeoutCallback(object State, bool TimedOut)
{
if (TimedOut)
{
HttpWebRequest Request = State as HttpWebRequest;
if (Request != null)
{
Request.Abort();
}
}
} public static void ReturnString(string TempStr,bool TempBool)
{
ReadStr = TempStr;
Suc = TempBool;
} }
public class RequestState
{
// This class stores the State of the request.
const int BUFFER_SIZE = 1024;
public StringBuilder RequestData;
public byte[] BufferRead;
public HttpWebRequest Request;
public HttpWebResponse Response;
public Stream StreamResponse;
public RequestState()
{
BufferRead = new byte[BUFFER_SIZE];
RequestData = new StringBuilder("");
Request = null;
StreamResponse = null;
}
} public class WebDataGather
{
private string ServerUrl = "http://web.com?id=" ;
public void StartGather()
{
for(int i=1;i<100;i++)
{
MyHttpWebRequest MyHttpWebRequest = new MyHttpWebRequest();
MyHttpWebRequest.MyDataGather(ServerUrl,i); string ReadStr = MyHttpWebRequest.ReadStr;
bool Suc = MyHttpWebRequest.Suc; if(Suc)
{
//输出ReadStr
}
} } }
}===================================================================大概就是这个样子的
但是 循环调用 异步下载的类 总会有问题//此处在循环第二次出现 未将对象引用设置到对象实例 的异常
MyRequestState.Response.Close();当把这里注释掉
执行没有问题 但是 后面字符串的输出会有问题 连续输出相同字符串 也就是循环调用的类执行时间长 而循环本身执行过快=========================================================
请朋友指明问题所在 并提出解决办法 谢谢
if(MyRequestState.Response !=null)