任务-财产分配 [英] Task - Property Assignment

查看:39
本文介绍了任务-财产分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初,我有以下内容:

foreach (Product product in products)
{
    product.ImageUri = _imageClient.GetImageUri(product.GetImagePath());
}

我想做的是并行处理所有产品,而不是一次处理一个.我已经将_imageClient.GetImageUri(...)更新为_imageClient.GetImageUriAsync(...).我现在可以执行以下操作:

What I would like to do is process all of the Products in parallel rather than one at a time. I have updated _imageClient.GetImageUri(...) to _imageClient.GetImageUriAsync(...). I can now do the following:

List<Task<Uri>> tasks = new List<Task<Uri>>();

foreach (Product product in products)
{
    Task<Uri> task = _imageClient.GetImageUriAsync(product.GetImagePath());
    tasks.Add(task);
}

var results = await Task.WhenAll(tasks);

这种方法的问题在于,我现在必须遍历结果,将每个结果与正确的Product匹配并分配属性.

The problem I have with this approach is that I now have to loop through the results, match each to the correct Product and assign the property.

有没有一种方法可以将这两种方法结合起来,以便我可以将属性分配作为任务的一部分,以便所有这些都可以并行运行?

Is there a way to combine the two approaches so that I can perform the property assignment as part of the task so that all can be run in parallel?

推荐答案

有关:

    List<Task<Uri>> tasks = new List<Task<Uri>>();

    foreach (Product product in products)
    {
        tasks.Add(Task.Run( async () =>  product.ImageUri = await _imageClient.GetImageUriAsync(product.GetImagePath()) ));
    }

    await Task.WhenAll(tasks);    

您甚至根本不需要结果.

You don't even really need the results in the end.

这篇关于任务-财产分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆