I am trying to learn / understand more about async / await in C # and I would put myself in the rookie category, so all your comments / suggestions are welcome. I wrote a small test to better understand and clarify what to expect / asynchronously. My program freezes after calling "GetStringLength", I tried to read a few things, but it looks like I'm stuck, and I thought about accepting an expert opinion on what I might do wrong. Can you please direct me or point me in the right direction?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncPatterns
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
Task<string> url = p.FindLargtestWebPage(new Uri[]{new Uri("http://www.google.com"),
new Uri("http://www.facebook.com"),
new Uri("http://www.bing.com") });
Console.WriteLine(url.Result);
Console.ReadLine();
}
public async Task<string> FindLargtestWebPage(Uri[] uris)
{
string highCountUrl = string.Empty;
int maxCount = 0;
foreach (Uri uri in uris)
{
Console.WriteLine(string.Format("Processing {0}", uri.ToString()));
var pageContent = await GetWebPageString(uri);
var count = await GetStringLength(pageContent);
if (count > maxCount)
{
highCountUrl = uri.ToString();
}
}
return highCountUrl;
}
public async Task<int> GetStringLength(string pageData)
{
Console.WriteLine("Getting length");
return await new Task<int>(() =>
{
return pageData.Length;
});
}
public async Task<string> GetWebPageString(Uri uri)
{
WebClient webClient = new WebClient();
Console.WriteLine("Downloading string");
return await webClient.DownloadStringTaskAsync(uri.ToString());
}
}
}
source
share