AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77462353
Accepted
David Thielen
David Thielen
Asked: 2023-11-11 03:13:15 +0800 CST2023-11-11 03:13:15 +0800 CST 2023-11-11 03:13:15 +0800 CST

Como executar o código quando o segundo método for concluído

  • 772

Tenho uma situação em que preciso executar algum código no final de 1 de 2 métodos - o que for concluído em segundo lugar. Meu caso particular é o servidor Blazor onde preciso executar este código no final de OnInitializedAsync()/OnAfterRenderAsync(). Nesse caso, o código depende de o JavaScript poder ser chamado e de o modelo da página ser totalmente preenchido a partir do banco de dados.

Eu criei a seguinte classe para fazer isso:

public class DoubleFinish
{
    private volatile bool _firstFinished = false;
    private volatile bool _secondFinished = false;
    private volatile bool _alreadyReturnedTrue = false;

    /// <summary>
    /// Call when the first method completes. Returns true if the 2nd method is also
    /// complete and so this method can now run the code that requires both methods.
    /// </summary>
    public bool TryFirstFinished
    {
        get
        {
            lock (this)
            {
                _firstFinished = true;
                if (_alreadyReturnedTrue || ! _secondFinished)
                    return false;
                _alreadyReturnedTrue = true;
                return true;
            }
        }
    }

    /// <summary>
    /// Call when the second method completes. Returns true if the 1st method is also
    /// complete and so this method can now run the code that requires both methods.
    /// </summary>
    public bool TrySecondFinished
    {
        get
        {
            lock (this)
            {
                _secondFinished = true;
                if (_alreadyReturnedTrue || ! _firstFinished)
                    return false;
                _alreadyReturnedTrue = true;
                return true;
            }
        }
    }
}

Então, em meu arquivo razor.cs, tenho o seguinte (os dois métodos em que estão podem estar em tarefas diferentes e, portanto, estar em execução ao mesmo tempo):

OnInitializedAsync() {
    // ... lots of DB access
    if (DoubleFinish.TryFirstFinished)
        await OnAfterInitializeAndRenderAsync();
}

OnAfterRenderAsync(bool firstRender) {
    if (!firstRender)
        return;
    if (DoubleFinish.TrySecondFinished)
        await OnAfterInitializeAndRenderAsync();
}

Eu tenho duas perguntas:

  1. Preciso declarar os bools em DoubleFinish volatile?
  2. Existe algum tipo de chamada atômica para verificar/definir os valores bool que evita o uso de lock?

Atualização: uma restrição importante. OnInitializedAsync()pode ser chamado duas vezes em algumas configurações. Então não posso usar um contador. Tenho que monitorar especificamente se cada método foi concluído.

c#
  • 2 2 respostas
  • 57 Views

2 respostas

  • Voted
  1. Theodor Zoulias
    2023-11-11T03:26:32+08:002023-11-11T03:26:32+08:00

    Acho que seria mais simples usar o Interlocked.Decrementmétodo, e diminuir atomicamente um contador inteiro. Quando o contador chegar a zero, você pode ter certeza de que a última operação pendente foi concluída:

    private int _pendingCount = 2;
    
    OnInitializedAsync()
    {
        // ...
        if (Interlocked.Decrement(ref _pendingCount) == 0)
            await OnAfterInitializeAndRenderAsync();
    }
    
    OnAfterRenderAsync()
    {
        // ...
        if (Interlocked.Decrement(ref _pendingCount) == 0)
            await OnAfterInitializeAndRenderAsync();
    }
    

    Atualizado: Caso cada um dos dois métodos possa ser chamado mais de uma vez, fica mais complexo, mas você ainda pode usar a Interlockedclasse. Aqui está uma implementação da operação OR bit a bit atômica para o uinttipo:

    /// <summary>
    /// Returns the result of an atomic bitwise OR operation.
    /// </summary>
    static uint AtomicBitwiseOr(ref uint location, uint operand)
    {
        uint oldValue = location;
        while (true)
        {
            uint newValue = oldValue | operand;
            uint original = Interlocked.CompareExchange(ref location, newValue, oldValue);
            if (original == oldValue) return newValue;
            oldValue = original;
        }
    }
    

    Poderia ser usado assim:

    private uint _state = 0;
    
    OnInitializedAsync()
    {
        // ...
        if (AtomicBitwiseOr(ref _state, 0b1) == 0b11)
            await OnAfterInitializeAndRenderAsync();
    }
    
    OnAfterRenderAsync()
    {
        // ...
        if (AtomicBitwiseOr(ref _state, 0b10) == 0b11)
            await OnAfterInitializeAndRenderAsync();
    }
    
    • 1
  2. Best Answer
    Guru Stron
    2023-11-11T03:44:04+08:002023-11-11T03:44:04+08:00

    Uma coisa que você pode fazer é usar Interlocked.Increment:

    private int counter = 2;
    
    OnInitializedAsync()
    {
        // ...
        if (Interlocked.Increment(ref counter) == 2)
            YourCodeToRun();
    }
    
    OnAfterRenderAsync(bool firstRender)
    {
        // ...
        if (Interlocked.Increment(ref counter) == 2)
            YourCodeToRun();
    }
    

    Ou SemaphoreSlimou AsyncCountdownEventde Nito.AsyncEx.Coordination. Algo como o seguinte (se for viável no contexto do Blazor):

    private AsyncCountdownEvent signal = new AsyncCountdownEvent(2);
    
    Task.Run(async () =>
    {
        await signal.WaitAsync();
        YourCodeToRun();
    })
    
    OnInitializedAsync()
    {
        // ...
        signal.Signal();
    }
    
    OnAfterRenderAsync(bool firstRender)
    {
        // ...
        signal.Signal();
    }
    

    Atualização

    Se OnInitializedAsyncpuder ser executado várias vezes, sua solução deverá funcionar bem. Observe que você deve evitar usar lock(this), basta criar um private object _locker = new object();campo para bloqueio e volátil não deve ser necessário, pois você está usando booleanos apenas dentro de bloqueios.

    Ou você pode brincar com essa monstruosidade (embora eu preferisse o bloqueio):

    private int flag1 = 0;
    private int flag2 = 0;
    private int hasRun = 0;
    
    OnInitializedAsync()
    {
        // ...
        Interlocked.Exchange(ref flag1, 1);
        if(Interlocked.Read(ref flag1) + Interlocked.Read(ref flag2) == 2 && Interlocked.Exchange(ref hasRun, 1) == 0)
            YourCodeToRun();
    }
    
    OnAfterRenderAsync(bool firstRender)
    {
        // ...
        Interlocked.Exchange(ref flag2, 1);
        if(Interlocked.Read(ref flag1) + Interlocked.Read(ref flag2) == 2 && Interlocked.Exchange(ref hasRun, 1) == 0)
            YourCodeToRun();
    }
    
    • 0

relate perguntas

  • Polly DecorrelatedJitterBackoffV2 - como calcular o tempo máximo necessário para concluir todas as novas tentativas?

  • Wpf. Role o DataGrid dentro do ScrollViewer

  • A pontuação que ganhei na página do jogo com .NET MAUI MVVM não é visível em outras páginas. Como posso manter os dados de pontuação no dispositivo local

  • Use a hierarquia TreeView com HierarchicalDataTemplate de dentro de um DataTemplate

  • Como posso melhorar essa interface de validação no .NET?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve