C#中使用lock和using語法
阿新 • • 發佈:2019-02-01
在反編譯photon原始碼的時候發現的,感到很有趣,以下是反編譯並補充完整的程式碼。
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace ExitGames.Threading { [StructLayout(LayoutKind.Sequential)] public struct Lock : IDisposable { private readonly object lockObject; private Lock(object obj) { this.lockObject = obj; Monitor.TryEnter(obj); } private Lock(object obj, int timeout) { this.lockObject = obj; if (!Monitor.TryEnter(obj, timeout)) { throw new LockTimeoutException(); } } public static IDisposable Enter(object syncObject) { return new Lock(syncObject); } public static IDisposable TryEnter(object syncObject, int millisecondsTimeout) { return new Lock(syncObject, millisecondsTimeout); } public void Dispose() { Monitor.Exit(this.lockObject); } } }
然後,去谷歌找啊找,找到這兩篇文章。2004年的老外寫的,嗚呼一下,現在才發現,幸好幸好。標題不知怎樣寫才好。
http://www.interact-sw.co.uk/iangblog/2004/03/23/locking
http://blogs.msdn.com/b/ericgu/archive/2004/03/24/95743.aspx