问题
Possible Duplicate:
Execute a WebRequest in a Background thread while UI Thread is blocked
Check out this code:
Thread t = new Thread((a) =>
{
var client = new WebClient();
client.DownloadStringAsync(new Uri("http://www.google.com"));
bool pointB = true;
});
t.Start();
t.Join(10000);
When this is run on the UI thread in Silverlight, even though DownloadStringAsync() is called quickly, pointB will not be reached until after the Join() times out. This means DownloadStringAsync() must somehow require the UI thread to do its work. Note: this has nothing to do with the callback to DownloadString. I know that WebClient's callbacks happen on the UI thread (see here: Silverlight Background Thread using WebClient).
The behavior of my code seems to indicate that the async invoke method itself (DownloadStringAsync()) also requires the UI thread. Is that right? And if so, why? I also want to note this same behavior is exhibited when using HttpWebRequest.BeginGetResponse()
Edit: to make things crystal clear, the order of operations I see when I step through this code is
- t.Start()
- t.Join(10000);
- var client = new WebClient();
- client.DownloadStringAsync(new Uri("http://www.google.com"));
- (... Join() timeout)
- bool pointB = true;
回答1:
Alright, I think I figured out the answer after a little more digging. It does seem indeed that all network code is ultimately run on the UI thread: http://nondestructiveme.com/2010/11/23/silverlight-and-networking-the-ui-thread/
The good news is it seems Microsoft fixed this "bug", as you might be justified in calling it, in Silverlight 5: http://msdn.microsoft.com/en-us/library/gg986857(VS.95).aspx
(At the bottom of the page under Performance Improvements: "Reduced network latency by using a background thread for networking. This is helpful for scenarios that use client HTTP web requests.")
I'll edit this answer once I test my code on Silverlight 5 to see if it indeed fixed the issue.
Edit: Built against Silverlight 5 and I'm still having the same problem. I think it's time for me to give up trying to block the UI thread at all...
来源:https://stackoverflow.com/questions/12289343/downloadstringasync-requires-ui-thread