我从不完全了解异步编程。
我有这种方法:

internal static Task gpUpdate(string pcName, string localUser, string localPass)
        {
            return Task.Run(() =>
            {
                string result = "";
                string command = @"/C psexec \\" + pcName + " /accepteula -s Gpupdate.exe /force";
                // string command = "/C winrs -r:" + pcName + " ECHO ON&echo N|Gpupdate.exe /force";
                Process process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.StandardOutputEncoding = Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.OEMCodePage);
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.FileName = "CMD.exe";
                process.StartInfo.WorkingDirectory = @"C:\Windows\System32";
                process.StartInfo.Arguments = command;
                process.StartInfo.UserName = Credentials.username;
                process.StartInfo.Password = Credentials.securePassword;
                process.StartInfo.Domain = "EPCE001N";
                process.Start();

                var output = process.StandardOutput.ReadToEnd();

                if (output.Contains("Aktualizace zásady uživatele byla úspěšně dokončena."))
                {
                    result = result + Environment.NewLine + pcName + " user GP update success...";
                }
                else
                {
                    result = result + Environment.NewLine + pcName + " user GP update failed...";
                }

                if (output.Contains("Aktualizace zásady počítače byla úspěšně dokončena."))
                {
                    result = result + Environment.NewLine + pcName + " computer GP update success...";
                }
                else
                {
                    result = result + Environment.NewLine + pcName + " computer GP update failed...";
                }

                PSEXEC.output = PSEXEC.output + Environment.NewLine + result;
            });
        }


我这样称呼它:

private async void gpUpdateBtn_Click(object sender, RoutedEventArgs e)
        {
            List<Task> tasks = new List<Task>();
            foreach (var pc in pcNamesListBox.Items)
            {
                tasks.Add(PSEXEC.gpUpdate(pc.ToString(), lclUsernameTxtBox.Text, lclPasswordTxtBox.Password));
            }

            Task.WaitAll(tasks.ToArray());
            textBlock.Text = PSEXEC.output;
        }


但是用户界面仍然死机,并且我在过去的2.5小时内都无法进行这项工作。有人可以调查一下吗?

最佳答案

您应该使用await Task.WhenAll而不是Task.WaitAll

关于c# - 异步仍然卡住ui,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52513470/

10-11 15:21