红俊's profile蝈蝈俊的共享空间PhotosBlogListsMore ![]() | Help |
|
April 29 MemberwiseClone与CloneMemberwiseClone 方法创建一个浅表副本,具体来说就是创建一个新对象,然后将当前对象的非静态字段复制到该新对象。如果字段是值类型的,则对该字段执行逐位复制。如果字段是引用类型,则复制引用但不复制引用的对象;因此,原始对象及其复本引用同一对象。 下面的代码就是演示这个问题: using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace CloneDemo { [Serializable] class DemoClass { public int i = 0; public int[] iArr = { 1, 2, 3 }; public DemoClass Clone1() { return this.MemberwiseClone() as DemoClass; } public DemoClass Clone2() { MemoryStream stream = new MemoryStream(); BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, this); stream.Position = 0; return formatter.Deserialize(stream) as DemoClass; } } class Program { static void Main(string[] args) { DemoClass a = new DemoClass(); a.i = 10; a.iArr = new int[] { 8, 9, 10 }; DemoClass b = a.Clone1(); DemoClass c = a.Clone2(); // 更改 a 对象的iArr[0], 导致 b 对象的iArr[0] 也发生了变化 a.iArr[0] = 88; Console.WriteLine("MemberwiseClone"); Console.WriteLine(b.i); foreach (var item in b.iArr) { Console.WriteLine(item); } Console.WriteLine("Clone2"); Console.WriteLine(c.i); foreach (var item in c.iArr) { Console.WriteLine(item); } Console.ReadLine(); } } } April 13 多线程Singleton单件模式Singleton模式是最简单的模式,比较汗颜的是自己一直以来使用的是单线程的Singleton模式,最近在听了李建忠老师的模式讲座录像后,才发现自己一直没注意到这点。这个录像讲座在后面给出了链接地址: C#面向对象设计模式纵横谈(2):Singleton 单件(创建型模式) 下面内容整理自李建忠老师的讲课内容: 单线程的Singleton模式 public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton Instance { get { if (instance == null) instance = new Singleton(); return instance; } } } 要点:
多线程的Singleton模式 public class Singleton { private static volatile Singleton instance = null; private static object lockHelper = new object(); private Singleton() { } public static Singleton Instance { get { if (instance == null) { lock (lockHelper) { if (instance == null) { instance = new Singleton(); } } } return instance; } } } 代码说明:
使用.net特有的支持多线程的单件模式代码 public sealed class Singleton { public static readonly Singleton Instance = new Singleton(); private Singleton() { } } 代码说明:
缺点:
参考资料: 讲讲volatile的作用
Implementing the Singleton Pattern in C#
初始化内联引用类型静态字段
通过七个关键编程技巧得益于静态内容
模式设计c#--创建型--Singleton
April 03 Thread.Sleep(0)今天在看 EnterpriseLibrary 源文件时,看到如下的代码,这个代码可以比较经典的解释Thread.Sleep(0)的用途。代码如下: Hashtable inMemoryCache; CacheItem cacheItemBeforeLock = null; // ..... 一些其他代码 Thread.Sleep(0); 线程挂起0毫秒。表面看来这个代码是没啥意义的。 其实不然,挂起0毫秒的意义不在于0毫秒,而在于挂起2个字,线程挂起,其他线程就有机会优先执行。 上面的代码中,在Thread.Sleep(0);之前,这个线程跟其他线程争抢cacheItemBeforeLock的情况,就会因为这个挂起而得到解决。 参考: 关于Thread.Sleep(0) Thread.Sleep 方法 (Int32) April 01 一个简单的演示SQL2005的查询通知的例子设置具体数据库启动Service Broker服务,如下图: 我这里试例数据库的名字为“ghj_Demo”,修改 Broker Enabled 属性为 true。 你也可以用SQL 语句来修改,修改的SQL语句如下: ALTER DATABASE ghj_Demo SET ENABLE_BROKER 确保你将使用的数据库帐户具有必需的权限 你在后面连接这个数据库的帐户,要确保对这个数据库具有 SUBSCRIBE、 QUERY 、NOTIFICATIONS 的权限。 下面就是一个简单的代码例子,来演示查询通知。这里用到一个我自己建立的表: 这个表结构如下: CREATE TABLE [dbo].[User]( [UserName] [nvarchar](20) NOT NULL, [Email] [nvarchar](50) NULL ) ON [PRIMARY] GO 演示的控制台代码如下: using System; using System.Data; using System.Data.SqlClient; namespace Demo { class Program { public static string connectionstring = "Data Source=.;Initial Catalog=ghj_Demo;Integrated Security=True"; public void DoDependency() { using (SqlConnection conn = new SqlConnection(connectionstring)) { // sql is a local procedure that returns // a paramaterized SQL string. You might want // to use a stored procedure in your application. string sql = "select [UserName] ,[Email] from dbo.[User]"; SqlCommand cmd = new SqlCommand(sql, conn); // Ensure the command object does not have a notification object. cmd.Notification = null; //Notification specific code SqlDependency dep = new SqlDependency(cmd); dep.OnChange += new OnChangeEventHandler(TestEvent); conn.Open(); SqlDataReader r = cmd.ExecuteReader(); //Read the data here and close the reader r.Close(); conn.Close(); Console.WriteLine("DataReader Read..."); } } void TestEvent(Object o, SqlNotificationEventArgs args) { // 注意: // 如果Server端在很短的时间内发生了大量的改动(比如用了一个循环Update了好多行), // OnChanged必须能迅速处理事件,否则它只会被触发一次。这个不是缺陷, // 因为一般OnChanged事件处理函数内都要执行类似刷新缓存的操作,它只触发一次, // 不会影响程序逻辑,却能提高程序性能。 Console.WriteLine("======================"); Console.WriteLine("Event Recd"); Console.WriteLine("Info:" + args.Info); Console.WriteLine("Source:" + args.Source); Console.WriteLine("Type:" + args.Type); } static void Main(string[] args) { // In order to use the callback feature of the // SqlDependency, the application must have // the SqlClientPermission permission. try { SqlClientPermission perm = new SqlClientPermission(System.Security.Permissions.PermissionState.Unrestricted); perm.Demand(); } catch { throw new ApplicationException("No permission"); } try { SqlDependency.Stop(connectionstring); //Start the listener infrastructure on the client SqlDependency.Start(connectionstring); Program q = new Program(); q.DoDependency(); Console.WriteLine("Wait for Notification Event..."); Console.Read(); } finally { //Optional step to clean up dependency else it will fallback to automatic cleanup SqlDependency.Stop(connectionstring); } } } } 一些注意事项:摘自MSDN文档 使用查询通知功能的应用程序需要考虑下列特殊注意事项。
编写通知查询语句的约束您可以为 SELECT 和 EXECUTE 语句设置通知。 使用 EXECUTE 语句时,SQL Server 会为执行的命令而不是 EXECUTE 语句本身注册通知。 该命令必须满足 SELECT 语句的要求和限制。 当注册通知的命令包含多个语句时,数据库引擎会为批处理中的每个语句创建一个通知。 对满足以下要求的 SELECT 语句支持查询通知:
sunmast 对查询通知的注意事情也有很多有价值的整理:
参考资料: 剖析SQL Server 2005查询通知之基础
Using SqlDependency for data change events
SQL Server 2005 Service Broker 初探
SQL Server 2005数据库开发详解
C# Windows 应用程序中实现 SQL Server 2005 查询通知
SqlDependency changes for RTM [Sushil Chordia]
.NET 2.0 SqlDependency快速上手指南
在 Windows 应用程序中使用 SqlDependency
Using SqlDependency in an ASP.NET Application Minimum Database Permissions Required for SqlDependency
使用SQL Server 2005 Query Notification的几个注意事项
|
|
|