Queuing asynchronous task in C#

前端 未结 4 1038
慢半拍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 14:53

    Building on your comment under Alexeis answer, your approch with the SemaphoreSlim is correct.

    Assumeing that the methods SendInstrumentSettingsToDS and SendModuleDataToDSAsync are members of the same class. You simplay need a instance variable for a SemaphoreSlim and then at the start of each methode that needs synchornization call await lock.WaitAsync() and call lock.Release() in the finally block.

    public async Task SendModuleDataToDSAsync(Module parameters)
    {
        await lock.WaitAsync();
        try
        {
            ...
        }
        finally
        {
            lock.Release();
        }
    }
    
    private async Task SendInstrumentSettingsToDS(, )
    {
        await lock.WaitAsync();
        try
        {
            ...
        }
        finally
        {
            lock.Release();
        }
    }
    

    and it is importend that the call to lock.Release() is in the finally-block, so that if an exception is thrown somewhere in the code of the try-block the semaphore is released.

提交回复
热议问题