public class Class1
{
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SendMessage(IntPtr hWnd, int Msg, int wParam, IntPtr lParam);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr CreateFileMapping(int hFile, IntPtr lpAttributes, uint flProtect, uint dwMaxSizeHi, uint dwMaxSizeLow, string lpName); [DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr OpenFileMapping(int dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, string lpName);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr MapViewOfFile(IntPtr hFileMapping, uint dwDesiredAccess, uint dwFileOffsetHigh, uint dwFileOffsetLow, uint dwNumberOfBytesToMap);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool UnmapViewOfFile(IntPtr pvBaseAddress);
[DllImport("Kernel32.dll", CharSet = CharSet.Auto)]
public static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32", EntryPoint = "GetLastError")]
public static extern int GetLastError();
const int ERROR_ALREADY_EXISTS = 183;
const int FILE_MAP_COPY = 0x0001;
const int FILE_MAP_WRITE = 0x0002;
const int FILE_MAP_READ = 0x0004;
const int FILE_MAP_ALL_ACCESS = 0x0002 | 0x0004;
const int PAGE_READONLY = 0x02;
const int PAGE_READWRITE = 0x04;
const int PAGE_WRITECOPY = 0x08;
const int PAGE_EXECUTE = 0x10;
const int PAGE_EXECUTE_READ = 0x20;
const int PAGE_EXECUTE_READWRITE = 0x40;
const int SEC_COMMIT = 0x8000000;
const int SEC_IMAGE = 0x1000000;
const int SEC_NOCACHE = 0x10000000;
const int SEC_RESERVE = 0x4000000;
const int INVALID_HANDLE_VALUE = -1;
IntPtr m_hSharedMemoryFile = IntPtr.Zero;
IntPtr m_pwData = IntPtr.Zero;
bool m_bAlreadyExist = false;
bool m_bInit = false;
long m_MemSize = 0;
public Class1()
{
}
~Class1()
{
Close();
}
///
/// 初始化共享内存
///
/// 共享内存名称
/// 共享内存大小
///
public int Init(string strName, long lngSize)
{
if (lngSize <= 0 || lngSize > 0x00800000) lngSize = 0x00800000;
m_MemSize = lngSize;
if (strName.Length > 0)
{
//创建内存共享体(INVALID_HANDLE_VALUE)
m_hSharedMemoryFile = CreateFileMapping(INVALID_HANDLE_VALUE, IntPtr.Zero, (uint)PAGE_READWRITE, 0, (uint)lngSize, strName);
if (m_hSharedMemoryFile == IntPtr.Zero)
{
m_bAlreadyExist = false;
m_bInit = false;
return 2; //创建共享体失败
}
else
{
if (GetLastError() == ERROR_ALREADY_EXISTS) //已经创建
{
m_bAlreadyExist = true;
}
else //新创建
{
m_bAlreadyExist = false;
}
}
//---------------------------------------
//创建内存映射
m_pwData = MapViewOfFile(m_hSharedMemoryFile, FILE_MAP_WRITE, 0, 0, (uint)lngSize);
if (m_pwData == IntPtr.Zero)
{
m_bInit = false;
CloseHandle(m_hSharedMemoryFile);
return 3; //创建内存映射失败
}
else
{
m_bInit = true;
if (m_bAlreadyExist == false)
{
//初始化
}
}
//----------------------------------------
}
else
{
return 1; //参数错误
}
return 0; //创建成功
}
///
/// 关闭共享内存
///
public void Close()
{
if (m_bInit)
{
UnmapViewOfFile(m_pwData);
CloseHandle(m_hSharedMemoryFile);
}
}
///
/// 读数据
///
/// 数据
/// 起始地址
/// 个数
///
public int Read(ref byte[] bytData, int lngAddr, int lngSize)
{
if (lngAddr + lngSize > m_MemSize) return 2; //超出数据区
bytData = new byte[(int)m_MemSize];
if (m_bInit)
{
Marshal.Copy(m_pwData, bytData, lngAddr, lngSize);
}
else
{
return 1; //共享内存未初始化
}
return 0; //读成功
}
///
/// 写数据
///
/// 数据
/// 起始地址
/// 个数
///
public int Write(byte[] bytData, int lngAddr, int lngSize)
{
if (lngAddr + lngSize > m_MemSize) return 2; //超出数据区
if (m_bInit)
{
Marshal.Copy(bytData, lngAddr, m_pwData, lngSize); }
else
{
return 1; //共享内存未初始化
}
return 0; //写成功
}
}
以上是网上找的源代码,在windows应用程序下可以正常使用,但是无法在Web上使用,哪位介绍个好用一点的类啊?谢谢如果跟调用Session或Application一样简单就好了,非常感谢,献上最后的分数。。如有好例子,欢迎email到: jun11th(a)gmail.com
解决方案 »
- 从数据库读取往本地写图片
- 请问DataGridView如何设置某一列的颜色?
- C# textbox 控件 按回车 执行 按钮事件应该怎么写代码?
- winform运行一段时间会报错(未将对象应用设置到对象的实例)
- 如保避免重复保存
- 如何消除C#控制台输入的行缓存
- vs配置文件出错!
- 请问怎样用C#写一个系统服务进程?
- 为什么我的vs2005,在创建一个对象后,输入部分对象名,但是智能框中却没有提示出对象。在完整输入对象名后,再输入一个点,也没有弹出相应方法。
- 接口 SQLDMO.NameList 的 QueryInterface 失败是什么意思?
- VS2008 web测试
- vs2005 下 c# 如何引入你想要的类
using System.Data;
using System.Collections;
using System.Diagnostics;
using System;
using System.Runtime.InteropServices;
using System.Text;namespace MemoryMappedCache
{
[Flags()]
internal enum Win32FileMapAccess : int
{
FILE_MAP_COPY = 1,
FILE_MAP_WRITE = 2,
FILE_MAP_READ = 4,
FILE_MAP_ALL_ACCESS = 983040 | FILE_MAP_COPY | FILE_MAP_WRITE | FILE_MAP_READ | 8 | 16
}
internal class ApiHelper
{
internal const int PAGE_READWRITE = 4;
internal const int SECURITY_WORLD_RID = 0;
internal const byte ACL_REVISION = 2;
internal const int WRITE_DAC = 0x40000;
internal const int WRITE_OWNER = 0x80000;
internal const int GENERIC_ALL = 0x10000000;
internal const int SECURITY_DESCRIPTOR_REVISION = 1;
internal const int SYNCHRONIZE = 0x100000;
internal const int STANDARD_RIGHTS_REQUIRED = 0xF0000;
internal const int MUTANT_QUERY_STATE = 0x1;
internal const int MUTEX_ALL_ACCESS = STANDARD_RIGHTS_REQUIRED + SYNCHRONIZE + MUTANT_QUERY_STATE;
internal const int MUTEX_MODIFY_STATE = 1;
internal const int STATUS_ABANDONED_WAIT_0 = 0x80;
internal const int STATUS_WAIT_0 = 0x0;
internal const int WAIT_TIMEOUT = 258;
internal const int WAIT_ABANDONED = ((STATUS_ABANDONED_WAIT_0) + 0);
internal const int WAIT_OBJECT_0 = ((STATUS_WAIT_0) + 0);
internal const int INFINITE = -1;
private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x1000;
[StructLayout(LayoutKind.Sequential)]internal struct ACL
{
internal byte AclRevision;
internal byte Sbz1;
internal short AclSize;
internal short AceCount;
internal short Sbz2;
}
[StructLayout(LayoutKind.Sequential)]internal struct ACE_HEADER
{
internal byte AceStructure;
internal byte AceFlags;
internal short AceSize;
}
[StructLayout(LayoutKind.Sequential)]internal struct ACCESS_DENIED_ACE
{
internal ACE_HEADER Header;
internal int Mask;
internal int SidStart;
}
[StructLayout(LayoutKind.Sequential)]internal struct SECURITY_DESCRIPTOR
{
internal byte Revision;
internal byte Sbz1;
internal int Control;
internal int Owner;
internal int Group;
internal ACL Sacl;
internal ACL Dacl;
}
[StructLayout(LayoutKind.Sequential)]internal struct ACCESS_ALLOWED_ACE
{
internal ACE_HEADER Header;
internal int Mask;
internal int SidStart;
}
[StructLayout(LayoutKind.Sequential)]internal struct SECURITY_ATTRIBUTES
{
internal int nLength;
internal int lpSecurityDescriptor;
internal int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]internal struct SID_IDENTIFIER_AUTHORITY
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.U1)]internal byte[] Value;
//Friend Value() As Byte
}
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int InitializeSecurityDescriptor(ref SECURITY_DESCRIPTOR pSecurityDescriptor, int dwRevision);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int SetSecurityDescriptorDacl(ref SECURITY_DESCRIPTOR pSecurityDescriptor, int bDaclPresent, IntPtr pDacl, int bDaclDefaulted);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int AllocateAndInitializeSid(ref SID_IDENTIFIER_AUTHORITY pIdentifierAuthority, byte nSubAuthorityCount, int nSubAuthority0, int nSubAuthority1, int nSubAuthority2, int nSubAuthority3, int nSubAuthority4, int nSubAuthority5, int nSubAuthority6, int nSubAuthority7, ref IntPtr lpPSid);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int GetLengthSid(ref IntPtr pSid);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int IsValidSid(IntPtr pSid);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int InitializeAcl(ref byte pAcl, int nAclLength, int dwAclRevision);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int AddAccessDeniedAce(ref byte pAcl, int dwAceRevision, int AccessMask, IntPtr pSid);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int AddAccessAllowedAce(ref byte pAcl, int dwAceRevision, int AccessMask, IntPtr pSid);
[DllImport("kernel32",EntryPoint="CreateMutexA", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int CreateMutex(ref SECURITY_ATTRIBUTES lpMutexAttributes, int bInitialOwner, string lpName);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern void FreeSid(ref IntPtr pSid);
[DllImport("advapi32.dll", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern IntPtr GetSidIdentifierAuthority(ref IntPtr pSid);
[DllImport("kernel32", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int ReleaseMutex(int hMutex);
[DllImport("kernel32",EntryPoint="OpenMutexA", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int OpenMutex(int dwDesiredAccess, int bInheritHandle, string lpName);
[DllImport("kernel32", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int WaitForSingleObject(int hHandle, int dwMilliseconds);
internal static int VarPtr(object o)
{
System.Runtime.InteropServices.GCHandle GC = System.Runtime.InteropServices.GCHandle.Alloc(o, System.Runtime.InteropServices.GCHandleType.Pinned);
int ret = GC.AddrOfPinnedObject().ToInt32();
GC.Free();
return ret;
}
[DllImport("kernel32",EntryPoint="CreateFileMappingA", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
public static extern int CreateFileMapping(IntPtr hFile, ref SECURITY_ATTRIBUTES lpFileMappigAttributes, int flProtect, int dwMaximumSizeHigh, int dwMaximumSizeLow, string lpName);
[DllImport("kernel32",EntryPoint="OpenFileMappingA", ExactSpelling=true, CharSet=CharSet.Ansi, SetLastError=true)]
public static extern int OpenFileMapping(int dwDesiredAccess, int bInheritHandle, string lpName);
[DllImport("kernel32",EntryPoint="MapViewOfFile", ExactSpelling=true, CharSet=CharSet.Auto, SetLastError=true)]
public static extern IntPtr MapViewOfFile(int hFileMappingObject, int dwDesiredAccess, int dwFileOffsetHigh, int dwFileOffsetLow, int dwNumberOfBytesToMap);
[DllImport("kernel32")]internal static extern bool UnmapViewOfFile(IntPtr lpBaseAddress);
[DllImport("kernel32", SetLastError = true)]internal static extern bool CloseHandle(IntPtr hFile);
[DllImport("kernel32")]private static extern int FormatMessage(int dwFlags, IntPtr lpSource, int dwMessageId, int dwLanguageId, StringBuilder lpBuffer, int nSize, IntPtr Arguments);
internal static string GetWin32ErrorMessage(int lcError)
{
StringBuilder strBuffer = new StringBuilder(1024);
int intLength = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, IntPtr.Zero, lcError, 0, strBuffer, 1024, IntPtr.Zero);
return strBuffer.ToString();
}
}
}
public sealed class Cache : IDisposable
{
private string m_strCacheName = "";
private Hashtable m_objCache = new Hashtable();public Cache(string lcCacheName)
{
Debug.Assert(! object.Equals(lcCacheName, null), "lcCacheName is nothing.");
Debug.Assert(lcCacheName.Length > 0, "lcCacheName is empty.");m_strCacheName = lcCacheName;
}private void ValidateKey(string lcKey)
{
if (object.Equals(lcKey, null) || lcKey.Length == 0)
{
throw (new ArgumentNullException("lcKey is null or empty."));
}lcKey = lcKey.Trim();
if (lcKey.Length > 100)
{
throw (new ArgumentException("lcKey is too long."));
}
}public void Assign(string lcKey, object lcData)
{
MemoryStream objMemoryStream = null;
BinaryFormatter objFormatter = null;
Mutex objMutex = null;
int intMapHandle = 0;
IntPtr objMapViewPointer = new IntPtr();ValidateKey(lcKey);
if (object.Equals(lcData, null))
{
throw (new ArgumentNullException("lcData is null."));
}try
{
objMemoryStream = new MemoryStream();
objFormatter = new BinaryFormatter();
objFormatter.Serialize(objMemoryStream, lcData);
objMemoryStream.Seek(0, SeekOrigin.Begin);
objMutex = new Mutex(GetMutexHandleName(lcKey));
objMutex.Wait();
string strName;
strName = GetFileMappingName(lcKey);
if (m_objCache.ContainsKey(strName))
{
Remove(lcKey);
}
ApiHelper.SECURITY_DESCRIPTOR objSecurityDescriptor = new ApiHelper.SECURITY_DESCRIPTOR();
int intResult = ApiHelper.InitializeSecurityDescriptor(ref objSecurityDescriptor, ApiHelper.SECURITY_DESCRIPTOR_REVISION);
if (intResult == 0)
{
throw (new Exception("InitializeSecurityDescriptor failed: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error())));
}intResult = ApiHelper.SetSecurityDescriptorDacl(ref objSecurityDescriptor, 1, new IntPtr(0), 0);
if (intResult == 0)
{
throw (new Exception("SetSecurityDescriptorDacl failed: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error())));
}ApiHelper.SECURITY_ATTRIBUTES objSecurityAttributes;
objSecurityAttributes = new ApiHelper.SECURITY_ATTRIBUTES();
objSecurityAttributes.nLength = Marshal.SizeOf(objSecurityAttributes);
objSecurityAttributes.bInheritHandle = 0;
objSecurityAttributes.lpSecurityDescriptor = ApiHelper.VarPtr(objSecurityDescriptor);intMapHandle = ApiHelper.CreateFileMapping(new IntPtr(-1), ref objSecurityAttributes, ApiHelper.PAGE_READWRITE, 0, System.Convert.ToInt32(objMemoryStream.Length + 4), strName);
if (intMapHandle == 0)
{
throw (new IOException("CreateFileMapping failed: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error())));
}m_objCache[strName] = intMapHandle;objMapViewPointer = ApiHelper.MapViewOfFile(intMapHandle, (int)Win32FileMapAccess.FILE_MAP_ALL_ACCESS, 0, 0, System.Convert.ToInt32(objMemoryStream.Length) + 4);
if (Equals(objMapViewPointer, IntPtr.Zero))
{
throw (new IOException("MapViewOfFile failed: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error())));
}
Marshal.WriteInt32(objMapViewPointer, 0, System.Convert.ToInt32(objMemoryStream.Length));
int intBytes;
int intPosition = 4;
byte[] arrBuffer = new byte[1024];
do
{
intBytes = objMemoryStream.Read(arrBuffer, 0, arrBuffer.Length);
if (intBytes > 0)
{
Marshal.Copy(arrBuffer, 0, new IntPtr(objMapViewPointer.ToInt32() + intPosition), intBytes);
intPosition += intBytes;
}
} while (intBytes == arrBuffer.Length);}
finally
{
if (! object.Equals(objMapViewPointer, IntPtr.Zero))
{
ApiHelper.UnmapViewOfFile(objMapViewPointer);
}
if (! object.Equals(objMutex, null))
{
objMutex.Release();
objMutex.Close();
}
if (! object.Equals(objMemoryStream, null))
{
objMemoryStream.Close();
}
}
}public object Contents(string lcKey)
{
int intMapHandle;
IntPtr objMapViewPointer = new IntPtr();
Mutex objMutex = null;
ValidateKey(lcKey);
objMutex = new Mutex(GetMutexHandleName(lcKey));
try
{
objMutex.Wait();
intMapHandle = ApiHelper.OpenFileMapping((int)Win32FileMapAccess.FILE_MAP_READ, 0, GetFileMappingName(lcKey));
if (intMapHandle <= 0)
{
//throw (new IOException("No cache named " + lcKey + " was found: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error())));
return null;
}BinaryReader objReader = null;
int intLength = 0;
try
{
objMapViewPointer = ApiHelper.MapViewOfFile(intMapHandle, (int)Win32FileMapAccess.FILE_MAP_READ, 0, 0, 4);
if (Equals(objMapViewPointer, IntPtr.Zero))
{
//throw (new IOException("MapViewOfFailed failed: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error())));
return null;
}
intLength = Marshal.ReadInt32(objMapViewPointer);}
finally
{
if (! object.Equals(objReader, null))
{
objReader.Close();
}
ApiHelper.CloseHandle(new IntPtr(intMapHandle));
if (! object.Equals(objMapViewPointer, IntPtr.Zero))
{
ApiHelper.UnmapViewOfFile(objMapViewPointer);
}
}if (intLength == 0)
{
return null;
}
intMapHandle = ApiHelper.OpenFileMapping((int)Win32FileMapAccess.FILE_MAP_READ, 0, GetFileMappingName(lcKey));
if (intMapHandle <= 0)
{
//throw (new IOException("OpenFileMapping failed: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error())));
return null;
}try
{
objMapViewPointer = ApiHelper.MapViewOfFile(intMapHandle, (int)Win32FileMapAccess.FILE_MAP_READ, 0, 0, intLength);
if (Equals(objMapViewPointer, IntPtr.Zero))
{
throw (new IOException(Marshal.GetLastWin32Error().ToString()));
}MemoryStream objMemoryStream;
byte[] arrBuffer = new byte[intLength + 1];
Marshal.Copy(new IntPtr(objMapViewPointer.ToInt32() + 4), arrBuffer, 0, intLength);
objMemoryStream = new MemoryStream(arrBuffer);objMemoryStream.Seek(0, SeekOrigin.Begin);
object obj = new BinaryFormatter().Deserialize(objMemoryStream);
objMemoryStream.Close();
return obj;
}
finally
{
ApiHelper.CloseHandle(new IntPtr(intMapHandle));
if (! object.Equals(objMapViewPointer, IntPtr.Zero))
{
ApiHelper.UnmapViewOfFile(objMapViewPointer);
}
}}
finally
{
objMutex.Release();
objMutex.Close();
}
return null;
}public void Remove(string lcKey)
{
string strName;
int intMapHandle;Mutex objMutex = null;
objMutex = new Mutex(GetMutexHandleName(lcKey));
try
{
objMutex.Wait();strName = GetFileMappingName(lcKey);
if (m_objCache.ContainsKey(strName))
{
intMapHandle = System.Convert.ToInt32(m_objCache[strName]);
ApiHelper.CloseHandle(new IntPtr(intMapHandle));
m_objCache.Remove(strName);
}
}
finally
{
objMutex.Release();
objMutex.Close();
}
}~Cache()
{
Dispose(false);
}public void Dispose()
{
GC.SuppressFinalize(this);
}private void Dispose(bool lcDisposing)
{
object synclockObject = this;
Monitor.Enter(synclockObject);
try
{
if (lcDisposing)
{
if (m_objCache.Count > 0)
{
string[] arrKeys = new string[m_objCache.Count-1 + 1];
int i;
m_objCache.Keys.CopyTo(arrKeys, 0);
for (i = 0; i <= arrKeys.GetUpperBound(0); i++)
{
Remove(arrKeys[i]);
}
}
}
}
finally
{
Monitor.Exit(synclockObject);
}
}private string GetFileMappingName(string lcKey)
{
return m_strCacheName + "mmf_" + lcKey;
}private string GetMutexHandleName(string lcKey)
{
return m_strCacheName + "mutex_" + lcKey;
}
}
using System.Collections;
using Microsoft.VisualBasic;
using System.Diagnostics;
using System;
using System.Runtime.InteropServices;
using System.Threading;namespace MemoryMappedCache
{
internal sealed class Mutex : IDisposable
{
private int mMutex = 0;
private string mName = "";
public Mutex(string lcName)
{
mName = lcName;
} private void Create()
{
IntPtr objSidEveryone = IntPtr.Zero;
ApiHelper.SECURITY_DESCRIPTOR objSecurityDescriptor = new ApiHelper.SECURITY_DESCRIPTOR();
int intResult = ApiHelper.InitializeSecurityDescriptor(ref objSecurityDescriptor, ApiHelper.SECURITY_DESCRIPTOR_REVISION);
if (intResult == 0)
{
throw new Exception("InitializeSecurityDescriptor failed: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error()));
} intResult = ApiHelper.SetSecurityDescriptorDacl(ref objSecurityDescriptor, 1, new IntPtr(0), 0);
if (intResult == 0)
{
throw new Exception("SetSecurityDescriptorDacl failed: " + ApiHelper.GetWin32ErrorMessage(Marshal.GetLastWin32Error()));
} ApiHelper.SECURITY_ATTRIBUTES objSecurityAttributes;
objSecurityAttributes = new ApiHelper.SECURITY_ATTRIBUTES();
objSecurityAttributes.nLength = Marshal.SizeOf(objSecurityAttributes);
objSecurityAttributes.bInheritHandle = 0;
objSecurityAttributes.lpSecurityDescriptor = ApiHelper.VarPtr(objSecurityDescriptor); mMutex = ApiHelper.CreateMutex(ref objSecurityAttributes, 0, mName);
if (mMutex == 0)
{
throw new Exception("CreateMutex failed: " + Marshal.GetLastWin32Error().ToString());
}
}
public void Wait()
{
int intResult;
Create();
intResult = ApiHelper.WaitForSingleObject(mMutex, ApiHelper.INFINITE);
switch (intResult)
{
case ApiHelper.WAIT_OBJECT_0:
return;
}
}
public void Release()
{
if (mMutex != 0)
{
if (ApiHelper.ReleaseMutex(mMutex) == 0)
{
throw (new Exception("ReleaseMutex failed: " + Marshal.GetLastWin32Error().ToString()));
}
mMutex = 0;
}
}
~Mutex()
{
Dispose(false);
}
private void Dispose(bool lcDisposing)
{
object synclockObject = this;
Monitor.Enter(synclockObject);
try
{
if (mMutex != 0)
{
ApiHelper.CloseHandle(new IntPtr(mMutex));
mMutex = 0;
}
}
finally
{
Monitor.Exit(synclockObject);
}
}
public void Dispose()
{
GC.SuppressFinalize(this); Dispose(true);
}
public void Close()
{
Dispose();
}
}
}
string name = "MyMMC_Cache_";
Cache a = new Cache(name);
object obj = a.Contents("TestDict");
if (obj != null)
{
Dictionary<Guid, string> dict = new Dictionary<Guid, string>();
try
{
dict = obj as Dictionary<Guid, string>;
foreach (Guid key in dict.Keys)
{
Response.Write(key.ToString() + "--->" + dict[key] + "<br>");
}
}
catch (Exception ex)
{
Response.Write("转换为 Dictionary 出错:" + ex.Message);
}
}
else
{
Response.Write("TestDict is null");
}