.Net is very helpful to program asynchronous and parallel. There are some good articles about that like this
But what is the best and in which context? I have just created a simple console application to try to figure out. It looks like async and await is faster, but it consumes more memory. This was the average result repeating the test three times in the same machine (CPU = AMD FX 8120 Eight-Core Processor 3,1GHz and RAM = 16GB):
Asynchronous Elapsed Time(s) = 23,0841498667 | Memory (MB) = 62154
Parallel Elapsed Time(s) = 107,9682892667 | Memory (MB) = 27828
The code is in GitHub and it is very simple.
The code requests webpages 250 times.
The Asynchronous test is that:
public async static Task AsynchronousTest()
{
List<Task<string>> taskList = new List<Task<string>>();
for (int i = 0; i < TOTAL_REQUEST; i++)
{
Task<string> taskGetHtmlAsync = GetHtmlAsync(i);
taskList.Add(taskGetHtmlAsync);
}
await Task.WhenAll(taskList);
//Trying to free memory
taskList.ForEach(t => t.Dispose());
taskList.Clear();
taskList = null;
GC.Collect();
}
public async static Task<string> GetHtmlAsync(int i)
{
string url = GetUrl(i);
using (HttpClient client = new HttpClient())
{
string html;
html = await client.GetStringAsync(url);
Trace.WriteLine(string.Format("{0} - OK (Html Length {1})", i + 1, html.Length));
return html;
}
}
And the parallel test is this:
public static void ParallelTest()
{
Parallel.For(0, TOTAL_REQUEST, i =>
{
string html = GetHtml(i);
});
}
public static string GetHtml(int i)
{
string html = null;
string url = GetUrl(i);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream receiveStream = response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8))
{
html = readStream.ReadToEnd();
}
}
}
Trace.WriteLine(string.Format("{0} - OK (Html Length {1})", i + 1, html.Length));
return html;
}
So, is there any way to improve the memory performance of the async/await method?
public static void SynchronousTest() { for (int i = 0; i < TOTAL_REQUEST; i++) { string html = GetHtmlAsync(i).Result; } }
– mqueirozcorreia Jan 08 '16 at 01:49