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);
}
};
What code should I write in order to execute a WebRequest in a background thread while the UI Thread is blocked?
EDIT:
…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);
};
I asked almost the exact same question here (which I’ll close now that I found yours):
DownloadStringAsync requires UI thread?
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…