Sunday, March 30, 2014

Problem with async method from .NET

I am always getting an empty string from this method:



private static string TranslateRequest(string input, string languagePair)
{
string result = "";
string url = String.Format("http://ift.tt/1pwJ3ZJ;, input, languagePair);

WebClient webClient = new WebClient();
webClient.Encoding = System.Text.Encoding.UTF8;

//HtmlAgilityPack.HtmlDocument document = new HtmlAgilityPack.HtmlDocument();
//document.LoadHtml(result);
//webClient.BaseAddress = url;

webClient.AllowReadStreamBuffering = true;
webClient.DownloadStringAsync(new Uri(url));


webClient.DownloadStringCompleted += (sender, e) =>
{
webClient.CancelAsync();
result = e.Result;
};

return result;
}

When I use this method in console application (in console application I can use synchronous method for downloading string), I get the result, but when I am using this code in Windows Phone 8 application (where I don't have synchronous method for downloading string; this pasted code is from Windows Phone project), I always get the empty string, like something wrong is happening on other thread.


Can anyone test this method in Windows Phone project and see what is the answer for this problem?




Development Technician, Microsoft Certified Professional


No comments:

Post a Comment