原文地址:http://www.codeproject.com/KB/architecture/TalkativeLockerPattern.aspx
我想要开发一个简单的设计模式,可以使开发人员更容易调试多线程的程序。在这篇文章中,我将介绍TalkativeLocker设计模式。TalkativeLocker模式的目的是将锁定的代码与其他的代码隔离开,只有单一点锁可以进入,获得,释放。下面是简单演示:
public class TalkativeLocker<T> { private readonly static object toLock = new object(); public T EnterLock(IClient client, Func<T> function) { T result = default(T); Console.WriteLine(client.Name + ":Waiting for lock"); Monitor.Enter(toLock); try { Console.WriteLine(client.Name + ":AquiredLock"); result = function(); } catch (Exception ex) { // } finally { Console.WriteLine(client.Name + ":About release lock"); Monitor.Exit(toLock); } return result; } }
TalkativeLocker
包括一个私有的对象toLock用于锁定。该对象是Static的,这就是说他是共享的,一次只有一个线程可以在他上面获得锁。
TalkativeLocker
还有一个Func<T>参数表示当获得锁的时候调用的程序。
下面看看如何使用
TalkativeLocker
类,先定义接口如下:
public interface IClient { string Name { get; set; } }
}
该接口只有一个Name属性,该属性可以让开发人员在调试多线程程序时更方便的显示相关调试信息。下面是该类的简单实现:
public class Client : IClient { private string name = String.Empty; private readonly TalkativeLocker<int> talkativeLocker = new TalkativeLocker<int>(); public Client(string name) { Name = name; } public string Name { get { return name; } set { name = value; } } public int AddTwoNumbers() { return 1 + 2; } public void DoSomething() { int result = talkativeLocker.EnterLock(this, AddTwoNumbers); } }
static void Main(string[] args) { Client[] clients = new Client[10]; clients[0] = new Client("1"); clients[1] = new Client("2"); clients[2] = new Client("3"); clients[3] = new Client("4"); clients[4] = new Client("5"); clients[5] = new Client("6"); clients[6] = new Client("7"); clients[7] = new Client("8"); clients[8] = new Client("9"); clients[9] = new Client("10"); foreach (Client client in clients) { Thread t = new Thread(client.DoSomething); t.Start(); } Thread.CurrentThread.Join(); Console.ReadLine(); }
运行结果如下: