如何向ASP.NET Web应用程序添加全局锁?

时间:2013-03-03 00:22:33

标签: c# asp.net locking

我正在编写一个使用C#的ASP.NET Web应用程序,可以从IIS服务器读取和写入文本文件(使用System.IO.FileStream),我想知道如何在此操作上实现全局锁定?

5 个答案:

答案 0 :(得分:3)

对于全局锁定,您需要mutex

    // 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();
    }   

答案 1 :(得分:1)

最简单的解决方案是在Cache或Application对象中创建一个新对象,最好是在global.asax文件中的Application_Startup中。如:

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

然后你可以使用标准"锁定"语法。

lock(Cache["myLocker"]) 
{
  // do file access here...
}

答案 2 :(得分:1)

为什么不只使用全局同步根对象?

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

用法:

lock (Lock.SyncRoot)
{
}

答案 3 :(得分:0)

从@Aristos的建议和this post,我想出了这个课程:

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
}

所以这似乎可以完成这项工作。你觉得怎么样?

答案 4 :(得分:0)

已命名的互斥锁是系统对象。与锁关键字不同,它们甚至可以跨进程边界工作。锁定仅在同步同一进程中的线程的情况下有用。