How can I check for a running process per user session?

后端 未结 4 1083
抹茶落季
抹茶落季 2021-01-02 13:42

I have a .NET application that I only allow to run a single process at a time of, however that app is used on Citrix boxes from time to time, and as such, can be run by mult

4条回答
  •  梦谈多话
    2021-01-02 14:18

    If Form1 launches non-background threads, and that Form1 exits, you've got a problem: the mutex is released but the process is still there. Something along the lines below is better IMHO:

    static class Program {
        private static Mutex mutex;
    
    
    
        /// 
        /// The main entry point for the application.
        /// 
        [STAThread]
        static void Main() {
            bool createdNew = true;
            mutex = new Mutex(true, @"Global\Test", out createdNew);
            if (createdNew) {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());        
            }
            else {
                MessageBox.Show(
                    "Application is already running",
                    "Error",
                    MessageBoxButtons.OK,
                    MessageBoxIcon.Error
                );
            }
        }
    }
    

    The mutex won't be released as long as the primary application domain is still up. And that will be around as long as the application is running.

提交回复
热议问题