簡體   English   中英

如何使用Async Await等到列表中的所有項目處理完畢-C#

[英]How to Wait until all Items processed in a list using Async Await - c#

我正在嘗試使用此代碼實現以下功能

1.我有項目清單,我希望以並行方式處理項目,以加快處理速度。

2.我也想等到列表中的所有數據得到處理並且需要更新數據庫中的相同內容

   private async Task<bool> ProceeData<T>(IList<T> items,int typeId,Func<T, bool> updateRequestCheckPredicate, Func<T, bool> newRequestCheckPredicate)
    {
            continueFlag = (scripts.Count > =12 ) ? true : false;
            await ProcessItems(items, updateRequestCheckPredicate, newRequestCheckPredicate);

            //Wait Until all items get processed and Update Status in database

            var updateStatus =UpdateStatus(typeId,DateTime.Now);
             return continueFlag;
    }

    private async Task ProcessItems<T>(IList<T> items,Func<T, bool> updateRequestCheckPredicate, Func<T, bool> newRequestCheckPredicate)
    {
       var itemsToCreate = items.Where(newRequestCheckPredicate).ToList();

        var createTask  = scripts
                     .AsParallel().Select(item => CrateItem(item);
                     .ToArray();
        var createTaskComplete = await Task.WhenAll(createTask);

        var itemsToUpdate = items.Where(updateRequestCheckPredicate).ToList();

        var updateTask = scripts
                   .AsParallel().Select(item => UpdateItem(item)
                   .ToArray();

        var updateTaskComplete = await Task.WhenAll(updateTask);
    }

     private async Task<ResponseResult> CrateItem<T>(T item)
    {
        var response = new ResponseResult();
         Guid requestGuid = Guid.NewGuid();
        auditSave = SaveAuditData(requestGuid);
        if (auditSaveInfo.IsUpdate)
        {
           response = await UpdateItem(item);
        }
        response = await CreateTicket<T>(item);
        // Wait response
        UpdateAuditData(response)
    }
    private async Task<ServiceNowResponseResult> CreateTicket<T>(T item)
    {
        // Rest call and need to wait for result
        var response = await CreateNewTicket<T>(scriptObj, serviceRequestInfo);
        return response;
    }

我是新來的等待異步概念的人,所以任何人都可以向我提出建議,無論我做的是正確的方法還是錯誤的方法請幫助我提供示例代碼

所有這些AsParallel是必需的,但您需要將回調的簽名更改為異步。

這是一個例子

    async Task ProcessAllItems<T>(IEnumerable<T> items,
        Func<T, Task<bool>> checkItem, // an async callback
        Func<T, Task> processItem)
    {
// if you want to group all the checkItem before any processItem is called
// then do WhenAll(items.Select(checkItem).ToList()) and inspect the result
// the code below executes all checkItem->processItem chains independently
        List<Task> checkTasks = items
            .Select(i => checkItem(i)  
            .ContinueWith(_ =>
            {
                if (_.Result)
                    return processItem(i);
                return null;
            }).Unwrap())   // .Unwrap takes the inner task of a Task<Task<>>
            .ToList();     // when making collections of tasks ALWAYS materialize with ToList or ToArray to avoid accudental multiple executions

        await Task.WhenAll(checkTasks);

    }

以及使用方法:

var items = Enumerable.Range(0, 10).ToList();
var process = ProcessAllItems(items,
    checkItem: async (x) =>
    {
        await Task.Delay(5);
        return x % 2 == 0;
    },
    processItem: async (x) =>
    {
        await Task.Delay(1);
        Console.WriteLine(x);
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM