編程新手,才學了幾個月。我正在制作一個 wpf 應用程式,用于啟動一些其他應用程式(.exe、.jar、.ahk)以實作 Minecraft Speedrunning 目的。
我正在嘗試找出一種啟動這些程式(主要是 MC 實體)的方法,而不會由于性能需求而完全凍結 WPF 主視窗(主視窗在 MC 實體啟動時凍結。完成后就可以了/在主選單中)。我想要這個的主要原因是因為 wpf 應用程式將具有其他功能,這些功能可能與啟動階段的訪問/使用相關。
要啟動 MC 實體,我使用 cmd 命令 MultiMC.exe -l [InstanceName]。為此,我使用檔案名為“cmd.exe”的 Process.Start(),引數為“MultiMC.exe -l [InstanceName]”,WorkingDirectory 是 MultiMC.exe 的目錄。
我一直在研究異步和執行緒(如多執行緒或并行執行緒)和 BackgroundWorker 之類的東西,但還沒有設法讓它作業(盡管很可能我只是沒有正確使用異步/執行緒,我真的不明白它)。
private static void processStarter(string directoryLocation, string cmdCommand)
{
ProcessStartInfo MCtask = new ProcessStartInfo();
MCtask.FileName = "cmd.exe";
MCtask.WindowStyle = ProcessWindowStyle.Hidden;
MCtask.Arguments = "/c " cmdCommand;
MCtask.RedirectStandardInput = true;
MCtask.RedirectStandardOutput = true;
MCtask.RedirectStandardError = true;
MCtask.WorkingDirectory = directoryLocation;
Process.Start(MCtask);
}
所以我想問題是 1:如何啟動這些實體,同時保持 WPF 主視窗回應用戶,例如其他按鈕按下;還有 2:是否有更好的方法來啟動這些實體?由于 MC 啟動器 (MultiMC) 使用的“-l [InstanceName]”命令,我沒有找到像這樣使用 CMD 的方法。
哦,我最初在控制臺應用程式中將這段代碼的基礎從 python 翻譯成 c#,因此出現了 RedirectStandardInput/Output/Error 行。
uj5u.com熱心網友回復:
您可以使用System.Windows.Threading命名空間和Thread類。
private static void processStarter(string directoryLocation, string cmdCommand)
{
MCtask = new ProcessStartInfo();
MCtask.FileName = "cmd.exe";
MCtask.WindowStyle = ProcessWindowStyle.Hidden;
MCtask.Arguments = "/c " cmdCommand;
MCtask.RedirectStandardInput = true;
MCtask.RedirectStandardOutput = true;
MCtask.RedirectStandardError = true;
MCtask.WorkingDirectory = directoryLocation;
Thread thread = new Thread(RunProcess);
thread.Start();
}
private static void RunProcess()
{
Process proc = new Process();
proc.StartInfo = MCtask; // MCtask will need to be some sort of global variable.
proc.Start();
proc.WaitForExit();
}
有一些方法可以將引數傳遞給執行緒函式(這樣你就可以傳遞MCtask并且它不必是全域的)但是你只能傳遞一個object必須被強制轉換的引數所以在我看來它不是一個非常好的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535113.html
標籤:C#wpf过程
