Queuing asynchronous task in C#

前端 未结 4 1044
慢半拍i
慢半拍i 2021-01-28 14:46

I have few methods that report some data to Data base. We want to invoke all calls to Data service asynchronously. These calls to data service are all over and so we want to mak

4条回答
  •  佛祖请我去吃肉
    2021-01-28 15:10

    Please keep in mind that your first solution queueing all tasks to lists doesn't ensure that the tasks are executed one after another. They're all running in parallel because they're not awaited until the next tasks is startet.

    So yes you've to use a SemapohoreSlim to use async locking and await. A simple implementation might be:

    private readonly SemaphoreSlim _syncRoot = new SemaphoreSlim(1);
    
    public async Task SendModuleDataToDSAsync(Module parameters)
    {
        await this._syncRoot.WaitAsync();
        try
        {
            foreach (var setting in Module.param)
            {
               await SaveModule(setting);
               await SaveModule(GetAdvancedData(setting));
            }
        }
        finally
        {
            this._syncRoot.Release();
        }
    }
    

    If you can use Nito.AsyncEx the code can be simplified to:

    public async Task SendModuleDataToDSAsync(Module parameters)
    {
        using var lockHandle = await this._syncRoot.LockAsync();
    
        foreach (var setting in Module.param)
        {
           await SaveModule(setting);
           await SaveModule(GetAdvancedData(setting));
        }
    }
    

提交回复
热议问题