【问题标题】:Is it possible to figure out when all Control.BeginInvoke(s) have been completed?是否可以确定所有 Control.BeginInvoke(s) 何时完成?
【发布时间】:2011-10-11 22:53:00
【问题描述】:

在我当前的项目中,我正在使用命令提示符,并根据在文本框中键入的输入并将其显示在 RichTextBox 上并按下按钮。

Having trouble with Process class while redirecting command prompt output to winform

我想做的一个小更新(可能不是一个特别小的更新 code-wize)是在命令提示符执行时让按钮处于“禁用”状态。由于该项目使用“Control.BeginInvoke”来更新richTextBox 上的文本,因此它是“一劳永逸”。这意味着一旦所有“BeginInvokes”都被处理到 UI 上,我就无法重新启用禁用的按钮。

我想问题是,是否有可能在所有“BeginInvokes”都执行后得到回调并说“嘿,我完成了,这是你的按钮返回。”这将防止用户点击按钮发送重复的进程。

这是我正在使用的代码的 sn-p:

public void GetConsoleOuput(string command = null)
{
    ProcessStartInfo startInfo = new ProcessStartInfo();
    startInfo.FileName = "cmd.exe";
    startInfo.RedirectStandardOutput = true;
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.UseShellExecute = false;
    startInfo.CreateNoWindow = true;

    if (!string.IsNullOrEmpty(command))
    {
        startInfo.Arguments = command;
    }

    Process process = new Process();
    process.StartInfo = startInfo;
    process.OutputDataReceived += new DataReceivedEventHandler(AppendRichBoxText);

    process.Start();
    process.BeginOutputReadLine();
    process.Close();
}

public void AppendRichBoxText(object sendingProcess, DataReceivedEventArgs outLine)
{
    string outputString = args.Data;
    MethodInvoker append = () => richTextBox.AppendText(outputString);
    richTextBox.BeginInvoke(append);
}

// Would like EventHandler method to enable button once all "BeginInvokes" are
// done running asynchronously due to a callback.
public void EnableButton
{
    /// re-enable a disabled button
}

【问题讨论】:

    标签: c# winforms delegates callback begininvoke


    【解决方案1】:

    在您完成所有更新后再次致电BeginInvoke,之后再致电EnabledButton

    【讨论】:

    • 根据提供的代码,我怎么知道什么时候是“在所有更新之后?”
    • 看起来 ProcessExit 事件挽救了这一天。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多