我在制作C#应用时遇到问题;我使用proc.Start();
作为启动其他应用。问题是这个方法运行指定的应用程序两次。我在Web上看了很多,但没有找到一个好的答案。代码段:
using (Process proc = Process.Start(BotProcess))
{
StatusLabel.Content = "Starting...";
proc.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);
proc.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_ErrorDataReceived);
proc.Start();
StatusLabel.Content = "Running";
proc.BeginOutputReadLine();
}
当它被执行时,在任务管理器中,我在应用程序中看到使用proc.Start()
的指定实例的2个进程。我该如何解决这个问题?
答案 0 :(得分:2)
正如评论回复中所述,你在使用声明的分配中启动了一次,然后再向下几行。
您想使用默认构造函数,然后设置您需要的内容,然后启动它。请参阅此示例here(也粘贴在下面):
using System;
using System.Diagnostics;
using System.ComponentModel;
namespace MyProcessSample
{
class MyProcess
{
public static void Main()
{
Process myProcess = new Process();
try
{
myProcess.StartInfo.UseShellExecute = false;
// You can start any process, HelloWorld is a do-nothing example.
myProcess.StartInfo.FileName = "C:\\HelloWorld.exe";
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();
// This code assumes the process you are starting will terminate itself.
// Given that is is started without a window so you cannot terminate it
// on the desktop, it must terminate itself or you can do it programmatically
// from this application using the Kill method.
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}