相关疑难解决方法(0)

为什么这个WebRequest代码很慢?

我要求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)

c# httpwebrequest httpwebresponse

12
推荐指数
2
解决办法
2万
查看次数

在ASP.NET MVC中未调用WebClient异步回调

在GET请求我运行(类似):

public ActionResult Index(void) {
    webClient.DownloadStringComplete += onComplete;
    webClient.DownloadStringAsync(...);
    return null;
}
Run Code Online (Sandbox Code Playgroud)

我发现onCompleteIndex()完成执行之后才会调用它.我可以看到,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)

asp.net-mvc multithreading

5
推荐指数
1
解决办法
2474
查看次数