创建计算线程总数和限制数量的异步方法
我正在尝试在我的 C# 应用程序中创建一个异步方法,并希望使用有限的线程来实现该方法,该方法应该在单独的线程中计算每个数组的许多数组的总和,但如果我们有超过 4 个(例如 6 个)数组,首先运行4 线程,一旦释放一个线程,您就需要再运行一个线程,依此类推。
这是我的代码:
static int CalculateRouter(Route route)
{
int total = route.sum(route.routers);
return total;
}
通过计算总时间异步计算最佳路线的异步方法 单独线程中的每个路由都需要。
public async Task <int> AsyncBestRoute(List<Route> Routes)
{
var tasks = new List<Task<int>>();
foreach (var route in Routes)
{
tasks.Add(Task.Run(() => CalculateRouter(route)));
}
int[] results = await Task.WhenAll(tasks);
int minValue = results.Min();
Console.WriteLine(minValue);
Console.WriteLine("********************");
return await Task.FromResult(minValue);
}
我的工作方法正确吗?我怎么能不限制线程呢?这是我第一次在其中工作,不知道应该如何拖延,有什么帮助或想法吗?
I'm trying to create a async method in my c# application and want to make it with limited threads the method should calculate the sum of many arrays each array in separate threads, but if we have more than 4 like 6 arrays, first you run 4
threads and once a thread is released you need to run one more and so on.
this is my code :
static int CalculateRouter(Route route)
{
int total = route.sum(route.routers);
return total;
}
Async method that calculates best route asynchronously by calculating total time
required for each route in a separate thread.
public async Task <int> AsyncBestRoute(List<Route> Routes)
{
var tasks = new List<Task<int>>();
foreach (var route in Routes)
{
tasks.Add(Task.Run(() => CalculateRouter(route)));
}
int[] results = await Task.WhenAll(tasks);
int minValue = results.Min();
Console.WriteLine(minValue);
Console.WriteLine("********************");
return await Task.FromResult(minValue);
}
is my work are correct in the method ? and how i can but limits of threads ? it's my first time to work within it and don't know how i should delay with it, there's any help or idea ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先:异步与并行有很大不同,尽管它们都是并发形式。异步的重点是使用更少线程,而并行性是使用更多线程。
由于您正在处理受 CPU 限制的操作(求和值),因此您需要并行性,而不是异步性。
Parallel
和 PLINQ 是这里合适的工具。一般来说,如果您有结果(或结果序列),PLINQ 会更干净一些。Parallel
和 PLINQ 都支持限制线程数量。如果您还需要异步,例如,如果您需要释放UI线程,那么您可以使用
await
和Task.Run
:First: asynchrony is quite different than parallelism, although they're both forms of concurrency. The whole point of asynchrony is to use fewer threads, and parallelism is to use more threads.
Since you're dealing with a CPU-bound operation (summing values), you want parallelism, not asynchrony.
Parallel
and PLINQ are the appropriate tools here. Generally, PLINQ is a bit cleaner if you have a result (or sequence of results). BothParallel
and PLINQ support limiting the number of threads.If you also need asynchrony, e.g., if you need to free up the UI thread, then you can use
await
andTask.Run
as such: