C#, 중복실행 체크 및 방지 코드

C#에서 프로그램 실행 시 이미 실행되고 있는 경우

실행되지 않도록 체크하고 방지해야 하는 일이 빈번히 발생한다.

아래 코드를 적어본다.

using System;
using System.Threading;
using System.Windows.Forms;


namespace runningCheck
{
    static class Program
    {
        

        /// 
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// 
        [STAThread]
        static void Main()
        {
            bool flag = true;
            bool USE_WATCHDOG = true;

            Mutex watchDog;

            // 필요에 따라 중복실행 체크를 안할 수도 있으므로
            // 사용여부를 보고 중복체크 실행
            if (USE_WATCHDOG)
            {
                /* 프로세스 중복실행 체크를 위한 코드 시작 */                
                watchDog = new Mutex(true, "VMU_WATCHDOG", out flag);

                if (flag)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new mainForm());

                    watchDog.ReleaseMutex();
                }
                else
                {
                    MessageBox.Show("프로그램이 이미 실행 중 입니다.", "오류");
                }
                /* 중복체크를 위한 코드 끝 */
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new mainForm());
            }
        }
    }
}
 

이상 끝!

댓글 없음:

댓글 쓰기

안녕하세요 :)