【发布时间】:2017-10-31 13:17:26
【问题描述】:
在我的 Windows 窗体程序中,我想实时读取批处理文件。搜索后,我找到了方法。但它只适用于控制台。如果我用richtextbox.appendtext 等替换console.writefile,它会显示“InvalidOperationException”。
这是我的代码
var process = new Process
{
StartInfo =
{
WorkingDirectory = @"C:\Users\Rayan\Desktop",
FileName = "cmd.exe",
Arguments = "/c test.bat",
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
}
};
process.OutputDataReceived += (s, e) => { richTextBox1.AppendText(e.Data + "\n"); };
process.Start();
process.BeginOutputReadLine();
process.WaitForExit();
我测试了很多东西,但没有任何效果。谢谢你的帮助, 聚甲基。
【问题讨论】:
-
OutputDataReceived 在与 UI 不同的线程上引发,您需要对控件进行线程安全调用。这是一个与您的问题几乎相同的问题stackoverflow.com/questions/5051550/cross-thread-problem
-
Cross Thread problem的可能重复
标签: c# batch-file command-line