Joerg said:
Here goes; it starts with button1_Click below.
///////////// TEST FORM ////////////////////////////////
private void button1_Click(object sender, System.EventArgs e)
{
string err = string.Empty;
listBox1.Items.Clear();
HTTPCaller caller = new HTTPCaller( txtURL.Text );
RequestState result = caller.beginRequest( ref err, new
AsyncCallback(this.httpCallback) );
if ( result == null )
{
MessageBox.Show( string.Format( "error calling begin request: {0}",
err) );
}
else
{
// Never true
while ( result.CompletedSynchronously ) ;
// Returns true immediately (before httpCallback is called )
while ( result.IsComplete ) ;
// Doesn't wait on anything (same as result.IsComplete)
//result.AsyncWaitHandle.WaitOne();
}
MessageBox.Show( "done" );
}
private void httpCallback( IAsyncResult ar )
{
RequestState requestState = (RequestState)ar.AsyncState;
HttpWebRequest webRequest = requestState.request;
try
{
using( HttpWebResponse response = webRequest.EndGetResponse(ar) as
HttpWebResponse )
{
using( StreamReader sr = new
StreamReader(response.GetResponseStream()) )
{
string temp = sr.ReadToEnd();
Monitor.Enter( listBox1 );
try
{
// just put the first few chars in a list box.
if ( temp.Length > 5 )
{
listBox1.Items.Add( temp.Substring(0, 5) );
}
}
finally
{
Monitor.Exit( listBox1 );
}
//Interlocked.Increment( ref callBackCount );
}
}
}
catch (Exception ex)
{
listBox1.Items.Add( ex.Message );
}
}
//////////////////////////////////////////////////////////
///////////// TEST OBJECT ////////////////////////////////
public class HTTPCaller
{
private string mUrl;
public HTTPCaller( string url )
{
mUrl = url;
}
public RequestState beginRequest( ref string err, AsyncCallback
callback )
{
RequestState result = null;
HttpWebRequest httpWebRequest = null;
try
{
httpWebRequest = HttpWebRequest.CreateDefault( new Uri(mUrl) ) as
HttpWebRequest;
RequestState requestState = new RequestState();
requestState.request = httpWebRequest;
if ( httpWebRequest.BeginGetResponse( callback, requestState ) !=
null ) result = requestState;
}
catch (Exception ex)
{
err = ex.Message;
}
return result;
}
}
//////////////////////////////////////////////////////////
///////////// HELPER OBJECT (MSDN) ///////////////////////
public class RequestState
{
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( string.Empty );
request = null;
streamResponse = null;
resetEvent = new AutoResetEvent(false);
}
}