在Silverlight WP7中伪造同步调用

CAC*_*lan 8 silverlight multithreading asynchronous windows-phone-7

我将一些代码从完整的.NET框架移植到WP7版本,我遇到了同步和异步调用的问题.

 string response;
 string requestString = GenerateReqString();
 HttpWebRequest req = (HttpWebRequest) WebRequest.Create("endpoint");
 req.Method = "POST";
 req.ContentType = "text/xml";

 req.ContentLength = requestString.Length;

 StreamWriter sw = new StreamWriter (req.GetRequestStream(), System.Text.Encoding.ASCII);
 sw.Write(requestString);
 sw.Close();

 StreamReader sr = new StreamReader(req.GetResponse().GetResponseStream());
 response = sr.ReadToEnd();
 sr.Close();
Run Code Online (Sandbox Code Playgroud)

然后将响应字符串解析为方法返回的对象列表.

我遇到的问题是没有办法在Silverlight/WP7中同步调用.如果我使用回调,我将在不同的函数中获得响应,并且无法从原始函数返回它.有没有办法同步进行调用或从CallBack函数返回到启动异步调用的方法?

Ada*_*lls 11

你需要以不同的方式思考问题.为了使异步事物"感觉"同步,最简单的方法是重构代码以使用" 延续传递样式 ".

本质上,您不是调用返回值的函数然后处理该值,而是调用函数,将匿名函数作为委托传递给它.然后被调用的函数将调用委托,传入字符串.

这是一个使用匿名函数和lambdas的示例:

void DoSomethingAsync( Action<string> callback ) {
    HttpWebRequest req; // TODO: build your request

    req.BeginGetResponse( result => {
        // This anonymous function is a closure and has access 
        // to the containing (or enclosing) function.
        var response = req.EndGetResponse( result );

        // Get the result string and call the callback
        string resultString = null; // TODO: read from the stream

        callback(resultString);
    }, null );
}
Run Code Online (Sandbox Code Playgroud)

这是解决方案的一半.接下来的部分是实际调用它.想象一下,你有一个ICommand实例或更简单的按钮点击事件,需要调用此函数并"获取字符串".而不是"获取字符串",而是调用此函数并提供回调方法(这将是一个闭包).

void btnGo_Click( object sender, EventArgs e ) {
    DoSomethingAsync( resultString => {
        // This anonymous function is called when the web request has
        // finished and has your string. 

        // Now that we have the string, we can go and process it.
        ProcessWebResponseResult( resultString );
    });
}
Run Code Online (Sandbox Code Playgroud)

这里是一个真正的好文章进一步解释这一概念: http://blogs.msdn.com/b/wesdyer/archive/2007/12/22/continuation-passing-style.aspx