gpt4 book ai didi

c# - 我正在尝试读取 c# 中进程的输出,但收到此消息 "Cannot mix synchronous and asynchronous operation on process stream."

转载 作者:太空狗 更新时间:2023-10-29 17:35:06 29 4
gpt4 key购买 nike

我正在使用 xcopy 编写一个备份程序,因为有很多大文件需要一段时间,所以我想显示进度。当我尝试使用 StreamReader 获取标准输出时,它在调试时出现此错误消息。 “不能在进程流上混契约(Contract)步和异步操作。”

  public void backup_worker_DoWork(object sender, DoWorkEventArgs e)
{
int loop = 1;

backup_worker.WorkerReportsProgress = true;

Process xcopy = new Process();
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.CreateNoWindow = true;
startinfo.UseShellExecute = false;
startinfo.RedirectStandardError = true;
startinfo.RedirectStandardOutput = true;
startinfo.FileName = Environment.CurrentDirectory + "\\xcopy.exe";
startinfo.Arguments = '"' + source + '"' + " " + '"' + target + '"' + " " + "/s /e /y";
xcopy.StartInfo.RedirectStandardOutput = true;
xcopy.StartInfo = startinfo;

xcopy.Start();
xcopy.BeginErrorReadLine();
xcopy.BeginOutputReadLine();

StreamReader sr = xcopy.StandardOutput;

while (loop > 0)
{
progress = sr.ReadLine();
output_list.Items.Add(progress);
}

xcopy.OutputDataReceived += new DataReceivedEventHandler(backup_worker_OutputDataRecieved);
xcopy.ErrorDataReceived += new DataReceivedEventHandler(backup_worker_ErrorDataReceived);
xcopy.WaitForExit();
backup_worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backup_worker_RunWorkerCompleted);
}

void backup_worker_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{

}

void backup_worker_OutputDataRecieved(object sender, DataReceivedEventArgs e)
{
}

void backup_worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
MessageBox.Show("Completed");
}

请帮忙。提前致谢

最佳答案

问题是您同时使用了同步和异步输出:

// Using async version here...
xcopy.BeginOutputReadLine();


StreamReader sr = xcopy.StandardOutput;

while (loop > 0)
{
// Trying to use synchronous reading here
progress = sr.ReadLine();

您需要将算法设计为使用一个选项或另一个选项,但不能同时使用两个选项。

关于c# - 我正在尝试读取 c# 中进程的输出,但收到此消息 "Cannot mix synchronous and asynchronous operation on process stream.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11460606/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com