问题
I need do download a string (specifically the JSON array result from a PHP webservice), as a function that returns a string, not DownloadStringAsync. I need this because I am writing a function that downloads the string, and then converts it to a JsonArray.
I am using Visual Studio Ultimate 2010, I am developing a Silverlight application, and any help will be appreciated.
回答1:
What you're looking for is not synchronous workflows (this would be very difficult, if not impossible, in Silverlight). Rather you want to be able to manage asynchronous workflows sequentially. You want to be able to say "Download this string from the web service, and then convert the string to a JSON array", without the messiness of handling callbacks and events.
Well there is good news and bad news. The good news is that there is a solution to this problem - it's called Coroutines. Coroutines are a way of halting execution of a sequential piece of code until the last part has completed, even if that part is asynchronous.
The bad news is that coroutines are not natively implemented in C# (although they are coming in C# 5). You can implement your own sequential workflows, and there is an absolutely brilliant article about it here. It's a long article and it's a little difficult if you've never done it before.
But despair not! There is a simpler way. Caliburn.Micro is an MVVM framework that actually has a simple coroutine implementation. In fact, you could quite easily use the Caliburn.Micro coroutines without using any other part of the framework, if you really want to. The creator of Caliburn.Micro, Rob Eisenberg, has an excellent article about coroutines, including theory and practice, here.
Basically your code will end up looking something like this:
public IEnumerable<IResult> DoTheThing() {
var json = new FetchString("webserviceaddress.asmx");
yield return json;
var jsonStr = json.Result;
var jsonArray = createJsonArray(jsonStr);
// do stuff with the array
}
At least I think that's what you're looking for :)
回答2:
Or if you're using MVVM Light, Matt Hamilton created coroutines for that framework: http://matthamilton.net/coroutines-with-mvvm-light
来源:https://stackoverflow.com/questions/5466020/synchronous-webclient-download-in-silverlight