相关疑难解决方法(0)

如何从控制台应用程序中的Task.WaitAll()获取返回值?

我使用控制台应用程序作为概念证明和获得异步返回值的新需求.

我发现我需要Task.WaitAll()在我的main方法中使用以避免需要异步"main()"方法,这是非法的.

我现在卡住试图弄清楚允许我使用泛型的重载,或者只返回我可以投射的对象,但是在Main()中.

.net c# console-application task-parallel-library async-await

36
推荐指数
2
解决办法
3万
查看次数

ForEachAsync 与结果

我正在尝试将Stephen Toub 的 ForEachAsync<T>扩展方法更改为返回结果的扩展......

斯蒂芬的扩展:

public static Task ForEachAsync<T>(this IEnumerable<T> source, int dop, Func<T, Task> body) 
{ 
    return Task.WhenAll( 
        from partition in Partitioner.Create(source).GetPartitions(dop) 
        select Task.Run(async delegate { 
            using (partition) 
                while (partition.MoveNext()) 
                    await body(partition.Current); 
        })); 
}
Run Code Online (Sandbox Code Playgroud)

我的方法(不起作用;任务被执行但结果是错误的)

public static Task<TResult[]> ForEachAsync<T, TResult>(this IList<T> source,
    int degreeOfParallelism, Func<T, Task<TResult>> body)
{
    return Task.WhenAll<TResult>(
        from partition in Partitioner.Create(source).GetPartitions(degreeOfParallelism)
        select Task.Run<TResult>(async () = 
        {
            using (partition)
                while (partition.MoveNext())
                    await body(partition.Current); // When I "return await",
                        // I get good results but only …
Run Code Online (Sandbox Code Playgroud)

c# concurrency asynchronous task-parallel-library parallel.foreachasync

1
推荐指数
1
解决办法
2390
查看次数