using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HttpClientStudy.Core.Utilities { /// /// 启动工具类 /// public static class StartupUtility { /// /// 启动webapi项目 /// (出现webapi项目启动命令行窗口) /// public static void StartWebApiProject() { string projectAndMutexName = WebApiConfigManager.GetWebApiConfigOption().CurrentValue.WebAppMutexName; //webapi项目不在运行状态则启动webapi项目 if (webAppIsRunningByMutex() == false) { //VS项目根目录 string vsProjectPath = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory)!.Parent!.Parent!.Parent!.Parent!.FullName; //webapi项目根项目 string webApiProjectPath = Path.Combine(vsProjectPath, projectAndMutexName); //启动命令信息 var prossInfo = new System.Diagnostics.ProcessStartInfo("dotnet", $"run --project {webApiProjectPath}") { UseShellExecute = true, CreateNoWindow = false, RedirectStandardOutput = false }; //启动 System.Diagnostics.Process.Start(prossInfo); } //由进程名判断 //bool webAppIsRunningByProcessName() //{ // return Process.GetProcessesByName(projectAndMutexName).ToList().Count == 0; //} //由互斥锁判断 bool webAppIsRunningByMutex() { bool createdResult = true; //创建互斥锁 using (var mutex = new Mutex(true, projectAndMutexName, out createdResult)) { if (createdResult) { mutex.ReleaseMutex(); } } //互斥锁是否创建成功 return !createdResult; } } /// /// 关闭webapi项目 /// public static void ExitWebApiProject() { string projectAndMutexName = WebApiConfigManager.GetWebApiConfigOption().CurrentValue.WebAppMutexName; //webapi为运行状态则关闭 if (webAppIsRunningByMutex()) { var webApiProcess = System.Diagnostics.Process.GetProcessesByName(projectAndMutexName); if (webApiProcess != null && webApiProcess.Length>0) { webApiProcess[0].Kill(); } } //由进程名判断 //bool webAppIsRunningByProcessName() //{ // return Process.GetProcessesByName(projectAndMutexName).ToList().Count == 0; //} //由互斥锁判断 bool webAppIsRunningByMutex() { bool createdResult = true; //创建互斥锁 using (var mutex = new Mutex(true, projectAndMutexName, out createdResult)) { if (createdResult) { mutex.ReleaseMutex(); } } //互斥锁是否创建成功 return !createdResult; } } } }