首页 > 解决方案 > 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).

标签: c#multithreadingasync-awaitparallel-processingtask-parallel-library

解决方案


正如其他人所指出的,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.
}

推荐阅读