diff --git a/Tasks/DT2/DT2.cs b/Tasks/DT2/DT2.cs index 8302b15..f744801 100644 --- a/Tasks/DT2/DT2.cs +++ b/Tasks/DT2/DT2.cs @@ -16,6 +16,7 @@ using System.Net.Security; using System.Diagnostics; using System.Threading.Tasks; using System.Threading; +using System.Buffers; namespace DT2 { public enum CallMode { Sync, Async, AsyncTimeout }; @@ -93,18 +94,29 @@ namespace DT2 { return size; } - /* TO BE DONE */ GetUrlAsync(string url) { + public async Task GetUrlAsync(string url) { PageStart(url); - /* TO BE DONE */ + int size = await Task.Run(() => GetPageSize(url)); PageLoaded(url, size); return size; } - /* TO BE DONE */ GetUrlAsyncTimeout(string url, int millis) { + public async Task GetUrlAsyncTimeout(string url, int millis) { + int size; PageStart(url); - /* TO BE DONE */ - - // PageLoaded or Timeout Event + Task task = Task.Run(() => GetPageSize(url)); + + try { + size = await task.WaitAsync(TimeSpan.FromMilliseconds(millis)); + PageLoaded(url, size); + } + catch (TimeoutException) + { + Timeout(url); + size = 0; + } + + return size; } @@ -112,6 +124,14 @@ namespace DT2 { // get a list of web addresses. int totalSize = 0; Stopwatch sw = Stopwatch.StartNew(); + + Action>> asyncRunner = (implementation) => + { + Task task = Task.WhenAll(urlList.Select((url) => implementation(url))); + task.Wait(); + totalSize = task.Result.Sum(); + }; + if (callMode == CallMode.Sync) { Console.WriteLine("\nCalling Sync"); foreach (var url in urlList) { @@ -120,11 +140,11 @@ namespace DT2 { } else if (callMode == CallMode.Async) { Console.WriteLine("\nCalling Async"); - /* TO BE DONE */ + asyncRunner.Invoke(GetUrlAsync); } else if (callMode == CallMode.AsyncTimeout) { Console.WriteLine("\nCalling Async Timeout"); - /* TO BE DONE */ + asyncRunner.Invoke((url) => GetUrlAsyncTimeout(url, 100)); } LoadSummary("Total", totalSize, (int)sw.Elapsed.TotalMilliseconds); }