geo*_*eek 5 .net c# process backgroundworker
在执行耗时的python脚本时,我会用后台工作者管理IU以显示进度条.
当我不需要事件时OutputDataReceived,我已成功使用后台工作程序,但我正在使用的脚本打印了一些进度值,如("10","80",..),所以我必须听取事件OutputDataReceived.
我得到这个错误:This operation has already had OperationCompleted called on it and further calls are illegal.在这一行progress.bw.ReportProgress(v);.
我试图使用2个后台工作器实例,一个执行而另一个监听,它没有给出任何错误,但它似乎没有调用事件'OutputDataReceived'所以我没有在进度条中看到任何进展.
在我使用的代码下面:
private void execute_script()
{
progress.bw.DoWork += new DoWorkEventHandler( //progress.bw is reference to the background worker instance
delegate(object o, DoWorkEventArgs args)
{
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "python.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.Arguments = @".\scripts\script1.py " + file_path + " " + txtscale.Text;
//proc.StartInfo.CreateNoWindow = true;
//proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
proc.StartInfo.RedirectStandardOutput = true;
//proc.EnableRaisingEvents = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardError = true;
proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(proc_OutputDataReceived);
proc.Start();
proc.BeginOutputReadLine();
//proc.WaitForExit();
//proc.Close();
});
progress.bw.RunWorkerAsync();
}
///the function called in the event OutputDataReceived
void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
//throw new NotImplementedException();
if (e.Data != null)
{
int v = Convert.ToInt32(e.Data.ToString());
MessageBox.Show(v.ToString());
// report(v);
progress.bw.ReportProgress(v);
}
else
MessageBox.Show("null received");
}
Run Code Online (Sandbox Code Playgroud)
问题是,BackgroundWorker的DoWork处理程序一旦启动过程结束,因为没有什么'等待’(因为你注释掉proc.WaitForExit()的过程来完成).一旦BackgroundWorker工作处理程序完成后,您可以使用该实例不再报告进度.
由于Process.Start已经是异步的,因此根本没有理由使用后台工作程序.您可以OutputDataReceived自己将调用编组到UI线程上:
///the function called in the event OutputDataReceived
void proc_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
//throw new NotImplementedException();
if (e.Data != null)
{
int v = Convert.ToInt32(e.Data.ToString());
// MessageBox.Show(v.ToString());
// progress.bw.ReportProgress(v);
this.BeginInvoke( new Action( () => {
this.progressBar.Value = v;
}));
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用此功能,请不要创建它BackgroundWorker.
| 归档时间: |
|
| 查看次数: |
8413 次 |
| 最近记录: |