Solve task 2
This commit is contained in:
parent
fad3634a3d
commit
183939309e
1 changed files with 28 additions and 8 deletions
|
@ -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<int> 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<int> GetUrlAsyncTimeout(string url, int millis) {
|
||||
int size;
|
||||
PageStart(url);
|
||||
/* TO BE DONE */
|
||||
Task<int> task = Task.Run(() => GetPageSize(url));
|
||||
|
||||
// PageLoaded or Timeout Event
|
||||
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<Func<string, Task<int>>> asyncRunner = (implementation) =>
|
||||
{
|
||||
Task<int[]> 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);
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue