2

我有多个REST API调用,我想以并行方式进行。例如

我有一个 REST API 调用CreateData()。我想在服务器中创建 1000 个数据,该数据适用于 4-5 个并行线程中的多线程操作。

我是 C++ 开发人员,知道多线程在 C++ 中的工作原理。我对 C# 编码很天真。我知道异步任务,但不知道如何完成上述任务。

var response = await Task.Run(()=>CreateData());

现在,我正在按顺序执行此操作,一旦收到先前CreateData()的响应,我将在单个线程中创建数据。它严重影响了性能并花费了大量时间。

我想创建 5 个线程,它们将以并行方式为所有 1000 个用户执行 REST API 调用。

4

2 回答 2

5

现在您正在分配response的结果在某些方面Task.Run还需要完成。Task这在编译时会自动发生,因为您使用的是关键字await

如果您愿意,您可以分配response给跑步Task本身并继续前进。我当然不会再叫它response了。假设您这样做并task1改为调用它。

var task1 = Task.Run(()=>CreateData());

现在您的代码将继续运行,并且task1仅代表正在运行的Task.

如果你有 5 个,你可以按照你想要的那样做。

var task1 = Task.Run(()=>CreateData());
var task2 = Task.Run(()=>CreateData());
var task3 = Task.Run(()=>CreateData());
var task4 = Task.Run(()=>CreateData());
var task5 = Task.Run(()=>CreateData());

Now you can also wait for all of these tasks to complete at the same time with Task.WhenAll method.

await Task.WhenAll(task1, task2, task3, task4, task5);

So to sum it up.

The await keyword does some compiler magic and basically puts a callback in that place of the method (assigning the rest of the method to be a continuation when the Task is complete) and ALSO assigns the Result of that Task to the variable (if the Task has a result). There is a lot to unpack here; I don't believe a short answer really justifies what's happening.

Without using the await keyword then you simply assign the Task itself to the variable.

于 2019-01-28T05:33:17.900 回答
2

你可以参考这个https://stackoverflow.com/a/25010220/4209924

或者

你可以做这样的事情。

    public async Task CreateData()
    {
        // your logic here with await
    }

    public async Task GetData()
    {
        var data1 = CreateData();
        var data2 = CreateData();
        var data3 = CreateData();
        var data4 = CreateData();
        await Task.WhenAll(new Task[] { data1, data2, data3, data4 });
    }
于 2019-01-28T05:32:00.400 回答