2 回答

TA貢獻1993條經(jīng)驗 獲得超6個贊
我過去通過創(chuàng)建源可執(zhí)行文件的副本解決了這個問題。在您的情況下,您可以:
將“original.exe”保存在特定位置。
每次需要調(diào)用它時,創(chuàng)建 original.exe 的副本并將其命名為“instance_xxxx.exe”,其中 xxxx 是唯一編號。
根據(jù)需要執(zhí)行您的新實例 exe,完成后您可以將其刪除
您甚至可以通過創(chuàng)建實例池來重用這些實例

TA貢獻1780條經(jīng)驗 獲得超4個贊
在 Dave Lucre 的回答的基礎上,我通過創(chuàng)建綁定到我的包裝類的可執(zhí)行文件的新實例來解決它。最初,我繼承IDisposable并刪除了 Disposer 中的臨時文件,但由于某種原因?qū)е虑謇頃枞麘贸绦虻膯栴},所以現(xiàn)在我的主程序最后執(zhí)行清理。
我的構造函數(shù)現(xiàn)在看起來像:
public AaTrend(string[] args, ILogger logger = null)
{
_logger = logger;
_logger?.WriteLine("Initialising new aaTrend object...");
if (args == null || args.Length < 1) args = new[] { "" };
_tempFilePath = GenerateTempFileName();
CreateTempCopy(); //Needed to bypass lazy single instance checks
HideTempFile(); //Stops users worrying
ProcessStartInfo info = new ProcessStartInfo(_tempFilePath, args.Aggregate((s, c) => $"{s} {c}"));
_process = new Process { StartInfo = info };
}
使用兩種新方法:
private void CreateTempCopy()
{
_logger?.WriteLine("Creating temporary file...");
_logger?.WriteLine(_tempFilePath);
File.Copy(AaTrendLocation, _tempFilePath);
}
private string GenerateTempFileName(int increment = 0)
{
string directory = Path.GetDirectoryName(AaTrendLocation); //Obtain pass components.
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(AaTrendLocation);
string extension = Path.GetExtension(AaTrendLocation);
string tempName = $"{directory}\\{fileNameWithoutExtension}-{increment}{extension}"; //Re-assemble path with increment inserted.
return File.Exists(tempName) ? GenerateTempFileName(++increment) : tempName; //If this name is already used, increment an recurse otherwise return new path.
}
然后在我的主程序中:
private static void DeleteTempFiles()
{
string dir = Path.GetDirectoryName(AaTrend.AaTrendLocation);
foreach (string file in Directory.GetFiles(dir, "aaTrend-*.exe", SearchOption.TopDirectoryOnly))
{
File.Delete(file);
}
}
作為旁注,這種方法僅適用于具有(惰性)確定實例化方法的應用程序,這些方法依賴于Process.GetProcessByName(); Mutex如果使用 a 或者如果在清單中明確設置了可執(zhí)行文件名稱,它將不起作用。
- 2 回答
- 0 關注
- 154 瀏覽
添加回答
舉報