0

C# のコンソール アプリケーションがあり、一度に 1 つのインスタンスのみを実行するようにアプリケーションを制限したいと考えています。あるシステムでは問題なく動作します。別のシステムで exe を実行しようとすると、動作しません。私は1つのexeしか開くことができません。別の PC で実行しようとすると、複数の exe を開くことができます。この問題を解決するにはどうすればよいですか? 以下は私が書いたコードです。

string mutexId = Application.ProductName;
using (var mutex = new Mutex(false, mutexId))
{
    if (!mutex.WaitOne(0, false))
    {
        MessageBox.Show("Instance Already Running!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
        return;
    }

        //Remaining Code here
}
4

2 に答える 2

1

とにかく、代わりにこのアプローチを使用します。

// Use a named EventWaitHandle to determine if the application is already running.

bool eventWasCreatedByThisInstance;

using (new EventWaitHandle(false, EventResetMode.ManualReset, Application.ProductName, out eventWasCreatedByThisInstance))
{
    if (eventWasCreatedByThisInstance)
    {
        runTheProgram();
        return;
    }
    else // This instance didn't create the event, therefore another instance must be running.
    {
        return; // Display warning message here if you need it.
    }
}
于 2013-01-16T10:03:34.957 に答える
0

私の古き良き解決策:

    private static bool IsAlreadyRunning()
    {
        string strLoc = Assembly.GetExecutingAssembly().Location;
        FileSystemInfo fileInfo = new FileInfo(strLoc);
        string sExeName = fileInfo.Name;
        bool bCreatedNew;

        Mutex mutex = new Mutex(true, "Global\\"+sExeName, out bCreatedNew);
        if (bCreatedNew)
            mutex.ReleaseMutex();

        return !bCreatedNew;
    }

ソース

于 2013-01-16T10:09:05.020 に答える