开发者

Async actions inside Silverlight Method - returning the value

开发者 https://www.devze.com 2022-12-24 00:57 出处:网络
What is the proper way to call an Async framework component - wait for an answer and then return the value. AKA contain the entire request/response in a single method.

What is the proper way to call an Async framework component - wait for an answer and then return the value. AKA contain the entire request/response in a single method.

Example code:

    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.
        }
    }

MORE INFO: The reason I'm asking this that I have a project I'm working on where I'd like JavaScript code in the browser to use Silverlight like a Facade/Proxy to Web services and complex calculations & operations. I'd like to make the calls to the [ScriptableMembers] in Silvelight synchronously. I don't want Silverlight to callback into the browser's JavaScript


Although blocking the UI with synchronous calls to the web server is certainly not-typical in a modern web application, you should be able to do what you want by careful use of ManualResetEvent.

Basically, you would cause GetSomeString in your example code to wait (WaitOne, preferably with a timeout) while the download is occurring, and upon failure or completion of the string download, you would trigger (Set) the event so that the blocking method in GetSomeString would then continue. You would need to put the result of the download somewhere in common with the caller, and make sure that it's thread safe.


Typically, I pass a reference object back from my first method. The callback method then modifies the object through a retained reference. The caveat is to ensure that you are on the UI thread if the object has properties displayed on screen.

0

精彩评论

暂无评论...
验证码 换一张
取 消