c# - Trigger Task method rapidly
问题描述
Command receiver:
public override async ValueTask Execute(){
// my code here
// this is boardcast command
// attempt #1
Parallel.ForEach(lists, async list => { await DoSomething(); });
// attempt #2
List<Task> tasks = new List<Task>();
foreach(ulong id in ids) tasks.Add(DoSomething());
await Task.WhenAll(tasks);
}
DoSomething():
public async Task DoSomething(){
Task<abc> Request = API.RequestSomething();
// attempt #1
await Request.ContinueWith(Callback => {
// Do something (long time...) , eg: update database, update all client data etc.
});
// attempt #2
await Request.ContinueWith(Callback => {
// .....
}, TaskContinuationOptions.ExecuteSynchronously);
}
Question is : If client sent command to receiver rapidly (about 100 commands per seconds), how can I handle this without (or low) delay, or how can I make my task function (Task DoSomeThing();
) run in parallel
I have tested my code and it works fine. But I would like your advice if there is a better way. Or is there any mistake that I'm missing? (I haven't tested it with multiple commands per second).
解决方案
正如其他人所指出的,Parallel
不应该与async
方法一起使用,因此该Task.WhenAll
方法是异步并发的正确解决方案:
public override async ValueTask Execute() {
var tasks = ids.Select(id => DoSomething()).ToList();
await Task.WhenAll(tasks);
}
关于您的实施,请勿使用ContinueWith
:
public async Task DoSomething() {
var Callback = await API.RequestSomething();
// Do something (long time...) , eg: update database, update all client data etc.
}
推荐阅读
- sql - 我在 SQL Server 中的存储过程出错
- node.js - npm install -g ethereumjs-testrpc 不工作?
- datetime - d3.timeParse("%Y") : 1895 年之前的日期未正确标记
- javascript - SharePoint 的客户端分类选择器
- extentreports - ExtentReports: detachReporter() 方法
- laravel - 迁移时添加多行
- javascript - 对工作日数组进行排序(JavaScript)
- gcov - 将 lcov 与 gcc-8 一起使用
- java - 如何为 Set Map of Sets 的 Java Map 声明 TypeScript 类型?
- nservicebus - AzureStorage 上的 NServiceBus 调度消息花费的时间超过了可见性超时