简体   繁体   中英

Issues with Button not changing when using Process.Start() in Blazor

I am having an issue where I want to change the button text while running a Process.Start(). Here's what I have:

<button class="btn-lg btn- @ButtonClass" disabled="@IsDisabled" @onclick="GenerateReports"><i class="@ButtonIcon"></i> @Button</button>

public partial class Index
    {
        private string Button { get; set; }
        private string ButtonClass { get; set; }
        private string ButtonIcon { get; set; }
        private bool IsDisabled { get; set; }

        protected override void OnInitialized()
        {
            Button = "Generate Reports";
            ButtonClass = "btn-primary";
            ButtonIcon = "fas fa-copy";
            IsDisabled = false;
        }

        private Task GenerateReports()
        {
            try
            {
                Button = "Please Wait. Reports Being Generated.";
                ButtonClass = "btn-secondary";
                ButtonIcon = "fas fa-spinner";
                IsDisabled = true;

                Process process = new Process();
                process.StartInfo.FileName = @"\\MyServer\E$\ObjectCode\Test.bat";
                process.StartInfo.RedirectStandardOutput = false;
                process.StartInfo.RedirectStandardError = false;
                process.StartInfo.UseShellExecute = false;
                process.Start();
                process.WaitForExit();

                Button = "Reports Generated!";
                ButtonClass = "btn-success";
                ButtonIcon = "fas fa-check";

                return Task.FromResult(true);
            }
            catch (Exception)
            {
                throw;
            }
        }

Basically, what I am trying to do is change the button text while disabling it. If I comment the Process part out, it works fine. However, once I run the Process it does not change the button nor disable it. Anything else I need to do in order for this work? Thanks in advance!

That is caused by the fact the button is being disabled and the text is being changed, but the UI is not updated before GenerateReports() exits.

You can split this function into two separate functions, one that will be called in order to start the process (and store it in private value), the second one would be called after the process has been completed.

For the second part you can use the approach described here: How to get notification that a System.Threading.Tasks.Task has completed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM