UI线程被阻止时,在后台线程中执行WebRequest [英] Execute a WebRequest in a Background thread while UI Thread is blocked

查看:88
本文介绍了UI线程被阻止时,在后台线程中执行WebRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当UI线程不再被阻塞时,以下代码为什么在5秒钟后执行WebRequest? Thread.Sleep位于UI线程中,而WebRequest的实例化和调用都发生在ThreadPool的线程内.

Why does the following code executes WebRequests after 5 secs when the UI Thread isn't being blocked anymore? Thread.Sleep is in the UI Thread while both Instantiation and Invocation of WebRequests occurring inside a Thread from ThreadPool.

Loaded += (sender, args) => {

    for (int i = 0; i < 5; i++) {

        ThreadPool.QueueUserWorkItem(state => {
            var request = WebRequest.CreateHttp("http://google.com");
            request.BeginGetResponse(ar => Debug.WriteLine("Request finished"), null);
        });

        Thread.Sleep(1000);
    }

};

当UI线程被阻止时,我应该编写什么代码才能在后台线程中执行WebRequest?

What code should I write in order to execute a WebRequest in a background thread while the UI Thread is blocked?

...更具体.为什么自从处于后台线程后的10秒钟后执行此请求?

...to be more specific. Why is this request being executed after 10 seconds since is in a background thread?

Loaded += (sender, args) => {

    ThreadPool.QueueUserWorkItem(state => {
        var request = WebRequest.CreateHttp("http://google.com");
        request.BeginGetResponse(ar => Debug.WriteLine("Request finished"), null);
    });
    Thread.Sleep(10000);

};

推荐答案

我在这里问了几乎完全相同的问题(在找到您的问题后,我将其关闭): DownloadStringAsync是否需要UI线程?

I asked almost the exact same question here (which I'll close now that I found yours): DownloadStringAsync requires UI thread?

答案是,所有网络代码最终都将在版本5之前的Silverlight中编组到UI线程中.不幸的是,即使我是针对Silverlight 5进行构建的,我仍然遇到相同的问题,因此我还在调查...

The answer is that ALL network code is ultimately marshaled to the UI thread in Silverlight before version 5. Unfortunately, even when I build against Silverlight 5, I'm still getting the same issue, so I'm still investigating...

这篇关于UI线程被阻止时,在后台线程中执行WebRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆