[英]C# Process - Pause or sleep before completion
我有一个过程:
Process pr = new Process();
pr.StartInfo.FileName = @"wput.exe";
pr.StartInfo.Arguments = @"C:\Downloads\ ftp://user:dvm@172.29.200.158/Transfer/Updates/";
pr.StartInfo.RedirectStandardOutput = true;
pr.StartInfo.UseShellExecute = false;
pr.StartInfo.
pr.Start();
string output = pr.StandardOutput.ReadToEnd();
Console.WriteLine("Output:");
Console.WriteLine(output);
Wput是ftp上传客户端。
在我运行该过程并开始上传的那一刻,该应用程序冻结并且控制台输出直到结束都不会显示。 我想第一个问题可以通过使用线程解决。
我想做的就是开始上传,让它每时每刻暂停,读取生成的任何输出(使用此数据做进度条等),然后重新开始。
我应该研究什么类/方法?
您可以使用OutputDataReceived
事件来异步打印输出。 要满足此要求,有一些要求:
在StandardOutput上的异步读取操作期间启用该事件。 要开始异步读取操作,您必须重定向Process的StandardOutput流,将事件处理程序添加到OutputDataReceived事件,然后调用BeginOutputReadLine。 此后,每次进程将一行写到重定向的StandardOutput流中时,都会发出OutputDataReceived事件信号,直到该进程退出或调用CancelOutputRead。
下面是此工作的一个示例。 它只是在执行一个长时间运行的操作,并且还会有一些输出(C:\\上的findstr /lipsn foo *
-在C驱动器上的任何文件中查找“ foo”)。 Start
和BeginOutputReadLine
调用是非阻塞的,因此您可以在FTP应用程序的控制台输出开始时执行其他操作。
如果要停止从控制台读取,请使用CancelOutputRead
/ CancelErrorRead
方法。 另外,在下面的示例中,我将使用单个事件处理程序来处理标准输出和错误输出,但是您可以将它们分开,并在需要时对其进行不同的处理。
using System;
using System.Diagnostics;
namespace AsyncConsoleRead
{
class Program
{
static void Main(string[] args)
{
Process p = new Process();
p.StartInfo.FileName = "findstr.exe";
p.StartInfo.Arguments = "/lipsn foo *";
p.StartInfo.WorkingDirectory = "C:\\";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(OnDataReceived);
p.ErrorDataReceived += new DataReceivedEventHandler(OnDataReceived);
p.Start();
p.BeginOutputReadLine();
p.WaitForExit();
}
static void OnDataReceived(object sender, DataReceivedEventArgs e)
{
Console.WriteLine(e.Data);
}
}
}
最好的方法是使用支持FTP的库,而不是依赖外部应用程序。 如果您不需要来自外部应用程序的大量信息并且不验证其输出,请继续。 否则,最好使用FTP客户端库。
可能是您想查看库/文档:
http://msdn.microsoft.com/en-us/library/ms229711.aspx
http://www.codeproject.com/KB/IP/ftplib.aspx
http://www.c-sharpcorner.com/uploadfile/danglass/ftpclient12062005053849am/ftpclient.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.