这是我现在的代码:
private string downloadContent()
{
try
{
WebRequest request = WebRequest.Create(url);
request.Method = "GET";
response = request.GetResponse();
Stream stream = response.GetResponseStream();
reader = new StreamReader(stream);
string content = reader.ReadToEnd();
return content;
}
catch
{
return error;
}
}
Run Code Online (Sandbox Code Playgroud)
这是网站:
http://chatroll.com/testings
Run Code Online (Sandbox Code Playgroud)
当我在聊天中写一些内容时,我就这样做,这样每隔n秒它就会显示我在程序textBox1中写的内容,并将其写在我硬盘上的文本文件记录器中.
问题是有时候如果我在聊天中输入的东西非常快(例如:你好(输入),嗨(输入),丹尼尔(输入))有时你的程序中不会显示你好.我不认为我输入内容的内容读得足够快.
有没有更快的方式来下载页面源并处理它?也许我下载它的方式不是那么快?
你可以在这里看到我的项目:
https://skydrive.live.com/redir?resid=3B8A7D9F66FF985B!171&authkey=!AFO6EmoF38MtkKQ
为什么不使用更高级别的WebClient?我不知道它是否更快,但至少它更不容易出错.您需要注意using
语句以释放任何资源(套接字等).
using (var downloader = new WebClient())
{
string result = downloader.DownloadString(url);
}
Run Code Online (Sandbox Code Playgroud)
编辑性能:如果Web服务器支持GZIP等压缩,您可能需要使用它:
设置标题:
downloader.Headers["Accept-Encoding"] = "gzip";
Run Code Online (Sandbox Code Playgroud)用于WebClient.DownloadData
将压缩响应加载到byte[]
.
GZipStream
另一个编辑:你的BackgroundWorker.DoWork看起来很糟糕:你有很多冗余代码,大量不必要的循环等等.我强烈建议你在Code Review上打开一个问题并发布该方法.顺便说一句,您在每次迭代时都会调用两次下载代码.
归档时间: |
|
查看次数: |
2803 次 |
最近记录: |