4

IISサーバーからテキストファイルを読み書きできるC#を使用してASP.NET Webアプリケーションを作成しています(を使用System.IO.FileStream)。この操作にグローバルロックを実装するにはどうすればよいですか?

4

5 に答える 5

3

グローバルロックにはミューテックスが必要です

    // The key can be part of the file name - 
    //   be careful not all characters are valid
    var mut = new Mutex(true, key);

    try
    {   
        // Wait until it is safe to enter.
        mut.WaitOne();

        // here you manipulate your file
    }
    finally
    {
        // Release the Mutex.
        mut.ReleaseMutex();
    }   
于 2013-03-03T00:44:35.353 に答える
1

The easiest solution would be to create a new object in the Cache or Application object, preferably in the Application_Startup within the global.asax file. Such as:

Cache["myLocker"] = new object();

Then you can use the standard "lock" syntax.

lock(Cache["myLocker"]) 
{
  // do file access here...
}
于 2013-03-03T00:58:14.937 に答える
1

@Aristos が提案したものとこの投稿から、私はこのクラスを思いつきました:

using System.Threading;
using System.Security.AccessControl;
using System.Security.Principal;

using System.Runtime.InteropServices;   //GuidAttribute
using System.Reflection;                //Assembly

namespace ITXClimateSaverWebApp
{
    public class GlobalNamedLock
    {
        private Mutex mtx;

        public GlobalNamedLock(string strLockName)
        {
        //Name must be provided!
            if(string.IsNullOrWhiteSpace(strLockName))
            {
                //Use default name
                strLockName = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
            }

            //Create security permissions for everyone
            //It is needed in case the mutex is used by a process with
            //different set of privileges than the one that created it
            //Setting it will avoid access_denied errors.
            MutexSecurity mSec = new MutexSecurity();
            mSec.AddAccessRule(new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null),
                MutexRights.FullControl, AccessControlType.Allow));

            //Create the global mutex
            bool bCreatedNew;
            mtx = new Mutex(false, @"Global\" + strLockName, out bCreatedNew, mSec);
        }

        public bool enterCRITICAL_SECTION()
        {
            //Enter critical section
            //INFO: May throw an exception!
            //RETURN:
            //      = 'true' if successfully entered
            //      = 'false' if failed (DO NOT continue!)

            //Wait
            return mtx.WaitOne();
        }

        public void leaveCRITICAL_SECTION()
        {
            //Leave critical section
            //INFO: May throw an exception!

            //Release it
            mtx.ReleaseMutex();
        }
    }
}

そして、グローバルロックのためにそれを呼び出す方法:

try
{
    GlobalNamedLock gl = new GlobalNamedLock("MyLockName");

    try
    {
        if (gl.enterCRITICAL_SECTION())
        {
            //Use the global resource now
        }
    }
    finally
    {
        gl.leaveCRITICAL_SECTION();
    }
}
catch (Exception ex)
{
    //Failed -- log it
}

だから、これは仕事をしているようです。どう思いますか?

于 2013-03-03T01:56:17.140 に答える
0

グローバル同期ルート オブジェクトを使用しないのはなぜですか?

internal static class Lock
{
    public static object SyncRoot = new object{};
}

使用法:

lock (Lock.SyncRoot)
{
}
于 2013-03-03T02:07:12.963 に答える