Search code examples
c#windows-phone-8windows-phone

Return inside event completed handler


I'm in the process of building this method which simply returns the content of a webpage. However, I can't return inside the event which is fired once the content is downloaded, getting this error:

Since 'System.Net.DownloadStringCompletedEventHandler' returns void, a return keyword must not be followed by an object expression.

If I take the return outside of the event, it won't fire after the download is complete, returning void and therefore making this useless

string ScrapePage(string url)
        {
            WebClient GetArticleHTML = new WebClient();
            GetArticleHTML.DownloadStringAsync(new Uri(url, UriKind.RelativeOrAbsolute));
            GetArticleHTML.DownloadStringCompleted += (s, x) =>
            {
                return x.Result;
            };
        }

Solution

  • Welcome to the world of asynchronous programming.

    You can't return in the event because events typically return void in .NET. In fact, by trying to do this, you are trying to force it to be synchronous! If your code worked, by the time the event handler was invoked, ScrapePage would have long completed, and you would be returning the value to, well, nothing, since the function had already returned!

    So you have two options:

    1. Make the method synchronous (using DownloadString instead of the async version) and return when its done. This might not be possible since you are on WP8, which likes async methods.

    2. Understand that the ScrapePage method simply starts the string download. The event handler will need to notify whoever wants the string that it is done downloading. It can then pass the downloaded string on a method call as a parameter.

    Realistically, you will want to do (2), especially if this is on the UI thread.