gpt4 book ai didi

c# - Silverlight 方法中的异步操作 - 返回值

转载 作者:太空宇宙 更新时间:2023-11-03 11:49:11 25 4
gpt4 key购买 nike

调用异步框架组件的正确方法是什么 - 等待答案然后返回值。 AKA 在一个方法中包含整个请求/响应。

示例代码:

    public class Experiment
{
public Experiment()
{

}
public string GetSomeString()
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted);
Uri u = new Uri("http://news.google.com/news?pz=1&cf=all&ned=us&hl=en&topic=t&output=rss");
wc.DownloadStringAsync(u);
return "the news RSS from Google";
}

private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{

//don't really see how this callback method makes it able
// to return the answer I'm looking for on the return
// statement in the method above.
}
}

更多信息:我问这个的原因是我有一个我正在处理的项目,我希望浏览器中的 JavaScript 代码使用 Silverlight,就​​像 Web 服务的 Facade/Proxy 和复杂的计算和操作。我想在 Silvelight 中同步调用 [ScriptableMembers]。我不希望 Silverlight 回调到浏览器的 JavaScript 中

最佳答案

虽然在现代 Web 应用程序中通过同步调用 Web 服务器来阻止 UI 肯定不是典型的,但您应该能够通过谨慎使用 ManualResetEvent 来完成您想要的操作。 .

基本上,您会导致示例代码中的 GetSomeString 在下载发生时等待( WaitOne ,最好有超时),并在失败完成时等待下载字符串时,您将触发 ( Set) 事件,以便 GetSomeString 中的阻塞方法将继续。您需要将下载结果放在与调用方相同的位置,并确保它是线程安全的。

关于c# - Silverlight 方法中的异步操作 - 返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2521085/

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