我要求100页,所有404.我写了
{
var s = DateTime.Now;
for(int i=0; i < 100;i++)
DL.CheckExist("http://google.com/lol" + i.ToString() + ".jpg");
var e = DateTime.Now;
var d = e-s;
d=d;
Console.WriteLine(d);
}
static public bool CheckExist(string url)
{
HttpWebRequest wreq = null;
HttpWebResponse wresp = null;
bool ret = false;
try
{
wreq = (HttpWebRequest)WebRequest.Create(url);
wreq.KeepAlive = true;
wreq.Method = "HEAD";
wresp = (HttpWebResponse)wreq.GetResponse();
ret = true;
}
catch (System.Net.WebException)
{
}
finally
{
if (wresp != null)
wresp.Close();
}
return ret;
}
Run Code Online (Sandbox Code Playgroud)
两次运行显示需要00:00:30.7968750和00:00:26.8750000.然后我尝试了Firefox并使用以下代码
<html> …
Run Code Online (Sandbox Code Playgroud) 在GET请求我运行(类似):
public ActionResult Index(void) {
webClient.DownloadStringComplete += onComplete;
webClient.DownloadStringAsync(...);
return null;
}
Run Code Online (Sandbox Code Playgroud)
我发现onComplete
在Index()
完成执行之后才会调用它.我可以看到,onComplete
在与Index
执行的线程不同的线程上调用它.
问题:为什么会发生这种情况?为什么webClient的异步线程显然被阻塞,直到请求处理线程完成?
有没有办法解决这个问题,而无需启动新线程ThreadPool
(我试过这个,并且使用线程池确实按预期工作.如果从ThreadPool的线程调用DownloadStringAsync,webClient的回调也会按预期发生).
ASP.NET MVC 3.0,.NET 4.0,MS Cassini开发Web服务器(VS 2010)
编辑:这是一个完整的代码:
public class HomeController : Controller {
private static ManualResetEvent done;
public ActionResult Index() {
return Content(DownloadString() ? "success" : "failure");
}
private static bool DownloadString() {
try {
done = new ManualResetEvent(false);
var wc = new WebClient();
wc.DownloadStringCompleted += (sender, args) => {
// this breakpoint …
Run Code Online (Sandbox Code Playgroud)