gpt4 book ai didi

multithreading - 在 Silverlight WP7 中伪造同步调用

转载 作者:行者123 更新时间:2023-12-04 06:27:54 25 4
gpt4 key购买 nike

我正在将一些代码从完整的 .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();

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

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

最佳答案

你需要以不同的方式思考问题。要使异步事物“感觉”同步,最简单的方法是重构代码以利用 ' continuation passing style '。

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

这是一个使用匿名函数和 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 );
}

这是解决方案的一半。下一部分是实际调用它。想象一下,您有一个 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 );
});
}

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

关于multithreading - 在 Silverlight WP7 中伪造同步调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3497874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com