如何转换iEnumerable< task< t>> ienumerable< lt; task< t>>>在C#中?
我有一个私人功能,它将 iEnumerable< func< task< t>>>
作为输入。我的任务< t>> 要通过。如何将转换为任务< t>>
ienumerable< func< task< task< t<
Code Sample:
private static async Task<IEnumerable<T>> ParallelizeAsync<T>(IEnumerable<Func<Task<T>>> funcs, int maxParallelism)
{
var sem = new SemaphoreSlim(maxParallelism, maxParallelism);
var result = funcs.Select(async f =>
{
await sem.WaitAsync();
var r = await f();
sem.Release();
return r;
});
return await Task.WhenAll(result);
}
var functasks = Enumerable.Range(1, 5).Select(async x => await Task.FromResult(x));
var help = ParallelizeAsync<IEnumerable<int>>(functasks, 10);
I'm getting the following error,
无法转换 'System.Collections.generic.Ienumerable&lt; system.threading.tasks.task&gt;' 到 'system.collections.generic.Ienumerable&lt; system.func&lt; system.threading.tasks.tasks.task&lt; system.collections.generic.eneric.ienumosite
我想念一些演员吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因此,您需要创建一个
Func
,当调用它时,它会返回您构造的已完成的Task
。最简单的方法很简单:所以要么:
要么给定
functasks
:您的另一个问题是您正在调用:
由于
ParallelizeAsync
的签名是:这意味着
T
是一个IEnumerable
,因此ParallelizeAsync
需要一个IEnumerable>>
。这与你的问题的其余部分不匹配。您可能打算调用
ParallelizeAsync(...)
。So, you'll want to create a
Func
which, when called, returns that already-completedTask
you constructed. The easist way is simply:So either:
Or given
functasks
:Your other problem is that you're calling:
Since the signature of
ParallelizeAsync
is:This means that
T
is anIEnumerable<int>
, soParallelizeAsync
is expecting anIEnumerable<Func<Task<IEnumerable<int>>>>
. This doesn't match the rest of your question.You probably intended to call
ParallelizeAsync<int>(...)
.对你来说,只需改变这一行
for you, just change this line
您需要将一个函数传递给返回另一个函数的
Select
:在这个简单的示例中,
async
/await
是多余的:请注意,您是还错误地调用了ParallelizeAsync;通过提供
IEnumerable
作为通用参数,funcs
变为IEnumerable>>>
。您应该简单地传递
int
:或者让类型推断来完成工作:
You need to pass a function to
Select
that returns another function:And in this simple example,
async
/await
are superfluous:Note that you are also calling
ParallelizeAsync
incorrectly; by providingIEnumerable<int>
as the generic argument,funcs
becomesIEnumerable<Func<Task<IEnumerable<int>>>>
.You should simply be passing
int
:Or let type inference do the work: