MUTEX를 사용하여 응용 프로그램의 단일 인스턴스를 실행하십시오

StackOverflow https://stackoverflow.com/questions/819773

  •  03-07-2019
  •  | 
  •  

문제

실행중인 응용 프로그램의 단일 인스턴스 만 허용하기 위해 MUTEX를 사용하고 있습니다. 코드는 아래에 나와 있습니다. 이것이 올바른 방법입니까? 코드에 결함이 있습니까?

사용자가 두 번째로 응용 프로그램을 열려고 할 때 이미 실행중인 응용 프로그램을 표시하는 방법. 현재 (아래 코드에서) 다른 인스턴스가 이미 실행 중이라는 메시지 만 표시하고 있습니다.

    static void Main(string[] args)
    {
        Mutex _mut = null;

        try
        {
            _mut = Mutex.OpenExisting(AppDomain.CurrentDomain.FriendlyName);
        }
        catch
        {
             //handler to be written
        }

        if (_mut == null)
        {
            _mut = new Mutex(false, AppDomain.CurrentDomain.FriendlyName);
        }
        else
        {
            _mut.Close();
            MessageBox.Show("Instance already running");

        }            
    }
도움이 되었습니까?

해결책

나는 이런 식으로 한 번했는데 도움이되기를 바랍니다.

bool createdNew;

Mutex m = new Mutex(true, "myApp", out createdNew);

if (!createdNew)
{
    // myApp is already running...
    MessageBox.Show("myApp is already running!", "Multiple Instances");
    return;
}

다른 팁

static void Main() 
{
  using(Mutex mutex = new Mutex(false, @"Global\" + appGuid))
  {
    if(!mutex.WaitOne(0, false))
    {
       MessageBox.Show("Instance already running");
       return;
    }

    GC.Collect();                
    Application.Run(new Form1());
  }
}

원천 : http://odetocode.com/blogs/scott/archive/2004/08/20/401.aspx

나는 이것을 사용한다 :

    private static Mutex _mutex;

    private static bool IsSingleInstance()
    {
        _mutex = new Mutex(false, _mutexName);

        // keep the mutex reference alive until the normal 
        //termination of the program
        GC.KeepAlive(_mutex);

        try
        {
            return _mutex.WaitOne(0, false);
        }
        catch (AbandonedMutexException)
        {
            // if one thread acquires a Mutex object 
            //that another thread has abandoned 
            //by exiting without releasing it

            _mutex.ReleaseMutex();
            return _mutex.WaitOne(0, false);
        }
    }


    public Form1()
    {
        if (!isSingleInstance())
        {
            MessageBox.Show("Instance already running");
            this.Close();
            return;
        }

        //program body here
    }

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (_mutex != null)
        {
            _mutex.ReleaseMutex();
        }
    }    

살펴보십시오 이 질문

이 기사에 대한 링크가 있습니다. 오해 MUTEX 뮤텍스 사용이 설명되는 곳.

표시된 코드 샘플을 확인하십시오 이 페이지

요컨대, 당신은 과부하 뮤트를 사용합니다 ctor(bool, string, out bool) 이름이 지정된 Mutex의 소유권이 있는지 아웃 매개 변수를 통해 알려줍니다. 첫 번째 인스턴스 인 경우 CTOR가 호출 된 후이 아웃 매개 변수는 참으로 포함됩니다.이 경우 평소와 같이 진행합니다. 이 매개 변수가 거짓 인 경우 다른 인스턴스가 이미 소유권을 가지고/실행중인 것을 의미합니다.이 경우 "다른 인스턴스가 이미 실행 중입니다"오류 메시지가 표시됩니다. 그런 다음 우아하게 나가십시오.

타임 아웃 및 보안 설정과 함께 앱을 사용하십시오. 내 커스텀 클래스를 사용했습니다.

private class SingleAppMutexControl : IDisposable
    {
        private readonly Mutex _mutex;
        private readonly bool _hasHandle;

        public SingleAppMutexControl(string appGuid, int waitmillisecondsTimeout = 5000)
        {
            bool createdNew;
            var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, AccessControlType.Allow);
            var securitySettings = new MutexSecurity();
            securitySettings.AddAccessRule(allowEveryoneRule);
            _mutex = new Mutex(false, "Global\\" + appGuid, out createdNew, securitySettings);
            _hasHandle = false;
            try
            {
                _hasHandle = _mutex.WaitOne(waitmillisecondsTimeout, false);
                if (_hasHandle == false)
                    throw new System.TimeoutException();
            }
            catch (AbandonedMutexException)
            {
                _hasHandle = true;
            }
        }

        public void Dispose()
        {
            if (_mutex != null)
            {
                if (_hasHandle)
                    _mutex.ReleaseMutex();
                _mutex.Dispose();
            }
        }
    }

그리고 그것을 사용하십시오 :

    private static void Main(string[] args)
    {
        try
        {
            const string appguid = "{xxxxxxxx-xxxxxxxx}";
            using (new SingleAppMutexControl(appguid))
            {

                Console.ReadLine();
            }
        }
        catch (System.TimeoutException)
        {
            Log.Warn("Application already runned");
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Fatal Error on running");
        }
    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top