8

【WPF】单例软件实现自重启 - 从南到北ss

 11 months ago
source link: https://www.cnblogs.com/younShieh/p/17749694.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

【WPF】单例软件实现自重启

原文地址 https://www.cnblogs.com/younShieh/p/17749694.html

❤如果本文对你有所帮助,不妨点个关注和推荐呀,这是对笔者最大的支持~❤

在WPF应用程序中,想要实现软件重启,可以再Start一次该软件的exe程序。
但是有些时候我们想要这个程序是唯一运行的单例,而不是可以多开的程序。那么在实现自重启时,需要释放当前的互斥体,然后再启动新的实例。以下是一个示例:

public partial class App : Application{ private static Mutex _mutex = null; const string appName = "MyAppName"; bool createdNew; protected override void OnStartup(StartupEventArgs e) { _mutex = new Mutex(true, appName, out createdNew); if (!createdNew) { //应用程序已经在运行!当前的执行退出。 Application.Current.Shutdown(); } base.OnStartup(e); } public void Restart() { // 释放互斥锁 _mutex.ReleaseMutex(); // 重启应用程序 System.Diagnostics.Process.Start(Application.ResourceAssembly.Location); Application.Current.Shutdown(); }}

我们添加了一个Restart方法,该方法首先释放互斥体,然后启动新的应用程序实例,最后关闭当前的应用程序。这样,新的应用程序实例就可以获取互斥体,而不会因为互斥体已经被占用而无法启动。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK