views:

273

answers:

3

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

+1  A: 

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.

WPCoder
+1  A: 

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.

Kirk
Any examples of this technique online that you can point me too? or can you share some example code?
tyndall