Async等待顶层处理

本文关键字:处理 等待 Async | 更新日期: 2023-09-27 18:03:13

我有大约10个SQL表,我需要提取数据、处理数据,然后将这些数据插入到另一个表中。我不想并行处理它们,但我想充分利用所有的IO时间。

我有一个函数:

    public async Task PromoteAsync()
    {
        try
        {
            using (HTTransDB transactions = new HTTransDB())
            using (ZImportMaster importMaster = new ZImportMaster())
            using (ZMasterAddress masterAddress = new ZMasterAddress())
            {
                // Select out non error rows
                DataTable dt = await HTTransDB.GetValidRowsAsync(this.TableConfig.BatchID, this.TableConfig.SourceTableName);

                // Do stuff
                // insert data
                using (HTTransDB transactionsDB = new HTTransDB())
                {
                    int result = await transactionDB.BulkCopyAsync(dt);
                }
            }
        }
        catch (Exception e)
        {
            // log exception and re-throw
        }
    }

我在每个表的foreach循环中运行这个函数:

    public async Task PromoteLoad()
    {
        // Load each batch
        foreach (var table in this.Tables)
        {
            await table.PromoteAsync();
        }
    }

我的问题是,我如何从非异步方法调用此函数?Task.Run吗?我不想启动新的线程,我只想让进程在等待IO时保持运行

Async等待顶层处理

您可以通过调用方法来启动异步工作:

var promoteTask = PromoteAsync();

请注意,返回的任务表示该方法的执行。