V
V
Vladimir Skachkov2020-07-08 08:32:03
C++ / C#
Vladimir Skachkov, 2020-07-08 08:32:03

Blazor-server app: how to make a dynamically updated variable on the page?

when you call StartCountDowan, the counter is dynamically decremented,
when you call ListFiles, the counter does not change, tell me how to solve this problem?

@page "/"

@using System
@using System.Net
@using System.IO
@using System.Globalization
@using System.Diagnostics
@using System.Threading

<h1>@count</h1>
<button @onclick="@StartCountDown">Start Countdown</button>
<button @onclick='@(() => ListFiles("ftp://ftpurl/"))'>Read</button>

@code {
   
    private int count { get; set; } = 10;

    protected override void OnInitialized()
    {
    }

    private async Task StartCountDown()
    {
        var timer = new Timer(new TimerCallback(_ =>
        {
            if (count <= 0) return;
            count--;
            InvokeAsync(() =>
            {
                StateHasChanged();
            });
        }), null, 1000, 1000);
    }

    private async Task ListFiles(string ftpPath)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpPath);
        request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
        request.Credentials = new NetworkCredential("Anonymous", "[email protected]");
        using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        using (Stream responseStream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(responseStream))
        {
            string line = reader.ReadLine();
            while (!string.IsNullOrEmpty(line))
            {
                ...
                await InvokeAsync(() =>
                {
                    count++;
                    StateHasChanged();
                });
                Debug.WriteLine (line); // вывод  работаем корректно
                ...                
                line = reader.ReadLine();                
            }
        }
    }  
}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question