Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/leayal/parallelasync
.NET System.Threading.Tasks.Parallel but with async.
https://github.com/leayal/parallelasync
async-await asynchronous dotnet-framework netstandard parallel
Last synced: 3 days ago
JSON representation
.NET System.Threading.Tasks.Parallel but with async.
- Host: GitHub
- URL: https://github.com/leayal/parallelasync
- Owner: Leayal
- License: unlicense
- Created: 2019-05-20T16:22:19.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2021-09-03T18:20:41.000Z (over 3 years ago)
- Last Synced: 2024-11-24T20:28:48.944Z (2 months ago)
- Topics: async-await, asynchronous, dotnet-framework, netstandard, parallel
- Language: C#
- Size: 17.6 KB
- Stars: 0
- Watchers: 1
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# ParallelAsync
.NET System.Threading.Tasks.Parallel but with async.## Example
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Threading;namespace ParallelAsync_Test
{
class Program
{
// C# 7.3 feature???? (Async Main)
public static async Task Main(string[] args)
{
// Prepare
string formatString = "http://example.com/text_file_{0}.txt";
Uri[] uris = new Uri[50];
for (int i = 0; i < uris.Length; i++)
{
uris[i] = new Uri(string.Format(formatString, i));
}HttpClient httpClient = new HttpClient();
ConcurrentDictionary result = new ConcurrentDictionary();// Allow Ctrl+C to cancel the async parallel download
CancellationTokenSource cancelSource = new CancellationTokenSource();
Console.CancelKeyPress += (sender, e) =>
{
cancelSource.Cancel();
};// Download 4 files in parallel until all 50 files are downloaded or until user request cancellation.
var loopResult = await ParallelAsync.ForEach(uris, new ParallelOptions() { MaxDegreeOfParallelism = 4, CancellationToken = cancelSource.Token }, async (uri) =>
{
result.TryAdd(uri, await httpClient.GetStringAsync(uri));
});
// Print the downloaded URLs and their text data.
foreach (var pair in result)
{
Console.WriteLine("==================================");
Console.WriteLine("URL: " + pair.Key.OriginalString);
Console.WriteLine("Data: " + pair.Value);
Console.WriteLine("==================================");
}if (!loopResult.IsCompleted)
{
Console.WriteLine();
Console.WriteLine("Loop ended prematurely because user has requested cancellation. Completed {0} loops.", loopResult.LowestBreakIteration.Value);
}Console.WriteLine();
Console.WriteLine("Press any key to close.");
Console.ReadKey();
}
}
}
```