Код представляет собой простое консольное приложение:
Код: Выделить всё
using DLWeb;
using System.Collections.Concurrent;
// initialize test data
ConcurrentBag _websites = [ new Website("BBC", "https://www.bbc.co.uk"),
new Website("Google", "https://www.google.com"),
new Website("Amazon","https://www.amazon.com")];
// set mode
bool USE_DOWNLOAD_ASYNC = true;
string mode = USE_DOWNLOAD_ASYNC ? "Asynchronously" : "Synchronously";
Console.WriteLine($"Starting (Running Download {mode})...{Environment.NewLine}");
ParallelLoopResult _loopRes = new();
if (USE_DOWNLOAD_ASYNC) // Async
{
await Task.Run(() =>
{
_loopRes = Parallel.ForEach(_websites, async (item) =>
{
var res = await DownloadAsync(item);
item.Content = res;
});
});
}
else
{
await Task.Run(() =>
{
_loopRes = Parallel.ForEach(_websites, (item) =>
{
string s = "";
s = Download(item.URL);
item.Content = s;
});
});
}
if (_loopRes.IsCompleted)
{
foreach (var item in _websites)
{
Console.WriteLine($"{item.Name}: {item.Content.Length}{Environment.NewLine}");
}
Console.WriteLine("Done.");
}
Console.ReadKey();
// ----------------------------------------------------
static string Download(string site)
{
HttpClient httpClient = new();
var r = httpClient.GetStringAsync(site).Result;
return r;
}
async static Task DownloadAsync(Website item)
{
HttpClient httpClient = new();
string res;
res = "" + await httpClient.GetStringAsync(item.URL);
return res;
}
Код: Выделить всё
public class Website
{
public string Name { get; set; } = "";
public string URL { get; set; } = "";
public string Content { get; set; } = "";
public Website()
{
}
public Website(string name, string url)
{
Name = name;
URL = url;
}
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... -loop-in-c
Мобильная версия