📄 5.2.txt
字号:
Listing 5.2 Asynchronous Delegates
using System;
using System.Threading;
using System.Runtime.Remoting.Messaging;
using System.Net;
using System.IO;
using System.Text;
namespace _5_AsynchronousDelegate
{
public delegate bool TearWebPage( string url );
class Class1
{
[STAThread]
static void Main(string[] args)
{
// create delegate attached to DoAsynchSleep method
TearWebPage tear = new TearWebPage( new WebTear().TearPage );
// create result class and create callback object
TearCallback result = new TearCallback();
AsyncCallback ascb = new AsyncCallback( result.PrintTearResult );
// invoke the delegate asynchronously
IAsyncResult ar = tear.BeginInvoke (
“http://www.samspublishing.com”, ascb, null );
// long operation here
Thread.Sleep(10000);
}
}
// Insert TearCallback implementation here
class WebTear
{
public bool TearPage( string url )
{
// final web page text variable
StringBuilder pageText = new StringBuilder(“”);
// create URI and a web request
Uri HttpSite = new Uri(url);
HttpWebRequest wreq = (HttpWebRequest)WebRequest.Create(HttpSite);
wreq.AllowAutoRedirect = true;
// get the stream associated with the web request
Stream webStream = wreq.GetResponse().GetResponseStream();
// create byte array for chunked data
byte[] webResponse = new byte[1024];
int bytesRead = 0;
do
{
// read first 1024 bytes
bytesRead = webStream.Read( webResponse, 0, 1024 );
// append current chunk to final result
if( bytesRead > 0 )
{
pageText.Append( Encoding.ASCII.GetString
( webResponse, 0, bytesRead ));
}
// continue until no more bytes are being read
} while( bytesRead > 0 );
// output final result
Console.WriteLine( pageText.ToString() );
return true;
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -