mercredi 23 août 2023

Async await Chain Responsibility Pattern

Hello i am having an issue using async and await in a Chain Responsibility Pattern, when the HandlerRequest is executed and an await operation is hitting another task is fire not waiting the first task to finish, so the first task doesn't finish and the second task finish exiting the method, leaving the first task uncompleted

Calling a queue of operations to execute

private async Task DoOperations(CancellationToken token)
{
    foreach (var operation in _operationDetails)
    {
        if (token.IsCancellationRequested)
        {
            return;
        }

        await h1.HandleRequest(operation.OperationTask);
    }
}

Handler

public abstract class Handler
{
    protected Handler successor;
    
    public void SetSuccessor(Handler successor)
    {
        this.successor = successor;
    }
    
    public abstract Task HandleRequest(OperationDetails.OPERATIONS operation);
}

Portion of code Handler h1

public override async Task HandleRequest(OperationDetails.OPERATIONS operation)
{
    if (operation == OperationDetails.OPERATIONS.SERVER_GET_AUDIO_LIST)
    {
        _updateLabelMessage?.Invoke(this, "Obteniendo lista de audios del servidor.");
        var result = await _services.AudioService.DownloadAudioListServerAsync(_token);
        _raiseRichTextInsertMessage?.Invoke(this, (result.status, result.statusMessage));
        if (result.status)
        {
            _getAudioListFiles?.Invoke(this, result.data);
        }
    }
    else if (successor != null)
    {
        successor.HandleRequest(operation);
    }
}

Portion of code Handler h3

public override async Task HandleRequest(OperationDetails.OPERATIONS operation)
{
    if (operation == OperationDetails.OPERATIONS.SERVER_DELETE_AUDIO)
    {
        _updateLabelMessage?.Invoke(this, "Eliminando audios del servidor");
        foreach (AudioFile file in _audioFileListToDelete)
        {
            _updateLabelMessage?.Invoke(this, "Eliminando audio: " + file.name);
            var result = await _services.AudioService.DeleteAudioServer(file.name, _token);
            _raiseRichTextInsertMessage?.Invoke(this, (result.status, result.statusMessage));
            if (_token.IsCancellationRequested)
            {
                _raiseRichTextInsertMessage?.Invoke(this, (false, "Operacion Cancelada."));
                return;
            }
        }
    }
    else if (successor != null)
    {
        successor.HandleRequest(operation);
    }
}

The first operation called is h3 but when this line of code is executed

var result = await _services.AudioService.DeleteAudioServer(file.name, _token);

The next handler (h1) is called not processing all the files in _audioFileListToDelete

Aucun commentaire:

Enregistrer un commentaire