我已经改变了问题的标题来反映这个问题我有,但是还就如何轻松地实现这个答案。
我试图让第二个方法返回Task<TResult>
而不是Task
作为第一个方法,但我得到错误的级联为试图解决它的后果。
- 我
await body(partition.Current);
- 前加入
return
反过来要求我先下添加,所以我下面 - 添加
return null
return语句但是现在的select语句抱怨说,它不能从查询 推断类型参数
- 我将
Task.Run
更改为Task.Run<TResult>
,但没有成功。
我怎样才能解决这个问题?
第一种方法来自http://blogs.msdn.com/b/pfxteam/archive/2012/03/05/10278165.aspx,第二种方法是,我试图创造过载。
public static class Extensions
{
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);
}));
}
public static Task ForEachAsync<T, TResult>(this IEnumerable<T> source, int dop, Func<T, Task<TResult>> 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);
}));
}
}
用例:
使用这种方法,我想下载并行且异步多个文件:
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
Artist artist = await GetArtist();
IEnumerable<string> enumerable = artist.Reviews.Select(s => s.ImageUrl);
string[] downloadFile = await DownloadFiles(enumerable);
}
public static async Task<string[]> DownloadFiles(IEnumerable<string> enumerable)
{
if (enumerable == null) throw new ArgumentNullException("enumerable");
await enumerable.ForEachAsync(5, s => DownloadFile(s));
// Incomplete, the above statement is void and can't be returned
}
public static async Task<string> DownloadFile(string address)
{
/* Download a file from specified address,
* return destination file name on success or null on failure */
if (address == null)
{
return null;
}
Uri result;
if (!Uri.TryCreate(address, UriKind.Absolute, out result))
{
Debug.WriteLine(string.Format("Couldn't create URI from specified address: {0}", address));
return null;
}
try
{
using (var client = new WebClient())
{
string fileName = Path.GetTempFileName();
await client.DownloadFileTaskAsync(address, fileName);
Debug.WriteLine(string.Format("Downloaded file saved to: {0} ({1})", fileName, address));
return fileName;
}
}
catch (WebException webException)
{
Debug.WriteLine(string.Format("Couldn't download file from specified address: {0}", webException.Message));
return null;
}
}
这并不完全清楚你期望的结果是什么。你传递了一系列'T'值,并在它们两个上执行相同的函数 - 你会期望从“Task'返回什么样的结果? –
我想在这种情况下得到一个任务,我已经在我的问题上添加了一个例子。 –
Aybe
*“使用这种方法,我想以并行和异步的方式下载多个文件”*:''Parallel.Foreach'还不够? –