Asynchronous programming provides a significant advantage for parallel tasks. However, managing the concurrency of these asynchronous operations is essential to avoid the system's overload. This article discusses common problems that restrict the number of I/O operations to restrict the number of I/O operations to ensure the best performance.
Question:
In the absence of the use of asynchronous HTTP requests concurrently to get multiple URLs, the default behavior is to create a large number of simultaneous requests. This may lead to exhaustion of resources and decline in performance. The challenge is to limit concurrency to the specified threshold, such as 20 requests at a time.
Solution:
.NET 4.5 Beta introduced an asynchronous signal volume (Semaphoreslim), which provided an effective method to control the concurrent access to resources. The Waitasync () method allows us to suspend the execution of the previously suspended asynchronous method before the specified number of slots. sample code:
In this code, the Waitasync () method ensures only 20 requests at a time. When a new request is arranged, it will wait until there is a groove to be available. A alternative solution to use task scheduling:
public async Task MyOuterMethod() { // 要获取的 URL 列表 string[] urls = { "http://google.com", "http://yahoo.com", ... }; // 创建一个节流器,将并发性限制为 20 个请求 SemaphoreSlim throttler = new SemaphoreSlim(initialCount: 20); // 初始化一个列表以存储所有异步任务 var allTasks = new List<Task>(); // 安排每个 URL 获取任务 foreach (var url in urls) { // 等待节流器中的一个槽可用 await throttler.WaitAsync(); // 在单独的线程池流中安排任务 allTasks.Add( Task.Run(async () => { try { using (var client = new HttpClient()) // 使用using语句确保HttpClient被正确释放 { var html = await client.GetStringAsync(url); } } finally { // 释放节流器中的槽 throttler.Release(); } })); } // 等待所有任务完成 await Task.WhenAll(allTasks); }
Another method involves the use of TPL -based scheduling to create commissioned binding tasks. Then you can implement a custom task scheduler to force the execution of concurrent restrictions. For more information, see examples of TaskscheDuler on MSDN.
The above is the detailed content of How to Limit Concurrent Async I/O Operations in .NET?. For more information, please follow other related articles on the PHP Chinese website!