当前位置: 移动技术网 > IT编程>开发语言>.net > 学习C#.NET、使用sqlserver数据库的总结

学习C#.NET、使用sqlserver数据库的总结

2020年04月07日  | 移动技术网IT编程  | 我要评论

刘琳个人资料,汽车台球,fornarina官网

介绍:之前没有学习过c#这个语言,我是刚刚从大学毕业的学生,我的专业是嵌入式系统工程(底层驱动arm、linux、单片机),本人很喜欢计算机,更喜欢软件开发(应用层)的这种工作,只是当时考大学时没有过多的了解选错了专业,毕业后开始找工作一直在找我喜欢的应用层行业,找了30多家公司终于有一个愿意培养我的了(主要是我不会应用层的技术,没有公司要我,所以找的公司很多,但我没放弃),在公司的三个月里我一边工作一边学习,现在把我所学到的都记录下来,下面有的代码我是复制其他人的,也别介意我是研究了好久了学会了,方便记录我就黏贴在我这里。大家可以学习,参考,指点错误,我也当个笔记方便以后复习。

有个提示:我是有过c语言底子的,学习c#时那些简单基础的语法很快就能懂得使用,我相信学过类似的语言(java、c++)都能一看就会那些简单基础,假如不会那请先学习编程的简单语法知识(我博客里也有简单语法知识),所以那些基础性东西我就不写了。我用的软件是vs2010,sqlserver2008。基础部分大多数是”控制台应用程序“,后面一点点延伸winform应用程序,web程序内的(html、css、javascript、jpuery、div+css)、mvc,asp.net。重点练习项目:超市管理系统、音乐播放器、局域网聊天(tcp/udp)、外网聊天(我相信很多程序员不会写)

想成功,多动脑!不要做个“手重眼轻”,能看会 未必能会写,很多都是用代码来讲解,全是“干货”。

接下来就是我这三个月的历程:

目录

一、基础

1.多态、继承

  1)、virtual虚方法多态

  2)、abstract抽象方法

2.泛型

  1)、泛型方法

  2)、泛型类

  3)、泛型接口

  4)、泛型约束

3.集合

  1)、泛型集合(list)

  2)、arraylist集合

  3)、dictionary键值对集合

  4)、hashtable键值对集合

  感觉少了什么,仔细想想我少写一个“枚举”,我就把枚举插在这个位置吧,临时在网上找的(不要夸我太懒,用到枚举的地方真的少,我就懒得写了)

  5)、枚举

4.拆装箱

5.逆变和协变

6.工厂模式

7.部分类partial

8.密封类sealed

9.重写tostring方法

10.属性

11.里氏转换is、as

12.接口

13.接口与抽象类的区别

14.流操作

15.序列化、反序列化(xml和二进制)

16.propertyinfo 反射

17.guid编号

18.stringbuilder

19.委托、事件

20.编写dll文件、调用dll文件、传参、返回值

21.字符串大小写转换

22.字符串大小写转换

23.单例模式

24.文件、文件夹操作(path、file、directory)

项目:----对基础知识的巩固复习

25.超市管理系统(控制台应用程序)

26.小游戏(石头剪刀布)

27.英汉词典

28.音乐播放器(winform)--------------这个软件会做了,才能代表c# winform开发 “基础”已经学会了

--------------------基础基本差不多了,等到全部结束后,我们再来更详细练习基础部分----------------------

 

二、线程

1.创建线程_前台_后台_挂起_唤醒_阻塞_终止_优先级

2.同步

3.线程池

4.异步

三、进程

1.进程简单操作

2.进程间通信

项目练习:映射综合

 

四、网络编程

 大概了解tcp、udp、socket工作原理,代码是如何编写的,先不需要立刻学会,下面我还会很详细你讲解的

了解部分:

1.tcp

2.udp

3.标准的socket

详细讲解:---->>>>(我花了两块五买的教程,拿出来了给大家分享,代码已经全是我亲手写的了)

1.复习委托机制

2.复习回调机制

3.tcp服务端

4.同步tcp客户端

5.异步tcp客户端

6.udp进程通信

7.udp广播和组播

8.局域网聊天室

9.webclient 

10.打洞(可以不用学 ,高端技术很难得)

项目练习:

    局域网聊天(简单)、

    局域网聊天(仿qq)、

    广域网聊天(仿qq,很难,学不会就不要学了,嘿嘿很多程序员都不会的)

    串口通讯(详细讲解,我认为串口要好好学习,现在的可以都是软件和硬件搭配的好才最值钱,就不过多解释了) 

---------------------------------------------------------------------------------------------------------------

数据库了

第一部分:

ac

my

sq

 他们的工作原理和操作

第二部分:

和winform的搭配使用

三层架构

项目:管理系统之类的

第三部分(自选喽)

ao很火

-----------------------------------------------------------------------------------------------------------------------------

wpf

把winform管理系统之类的项目改写成wpf

----------------------

asp.net

html css js jq  mvc

把winform管理系统之类的项目改写成asp.net

--------------------------------------------

细致化的复习winform控件之类的知识

-----------------------------------------

在来几个其他技术

---------------------------------------

结束!发言

 

 

 

 

 

 

 

一、基础

1.多态、继承 

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //实现多态的手段
 7 //1)、虚方法
 8 //步骤:
 9 //1、将父类的方法标记为虚方法 ,使用关键字 virtual,这个函数可以被子类重新写一个遍。
10 //理解:通过继承实现的不同对象调用相同的方法,表现出不同的行为,称之为多态。
11 
12 //2)、抽象类
13 //当父类中的方法不知道如何去实现的时候,可以考虑将父类写成抽象类,将方法写成抽象方法。
14 //派生类要实现抽象方法,派生抽象类可以不用重写父类抽象方法
15 //抽象类和接口 很像,我会在写接口时介绍他俩的区别
16 
17 //3)、继承
18 //新类(即派生类)将获取基类的所有非私有数据和行为以及新类为自己定义的所有其他数据或行为。
19 //子类实现父类的属性和方法,并在此基础上进行相关的扩展
20 
21 //下面是虚方法的多态:
22 namespace _1.多态_虚方法_
23 {
24     public class animal
25     {
26         public virtual void eat()//虚方法 virtual
27         {
28             console.writeline("动物会吃东西");
29         }
30     }
31 
32     public class dog : animal//继承animal animal为父类
33     {
34         public override void eat()//重写虚方法 override
35         {
36             console.writeline("狗也会吃东西");
37         }
38     }
39 
40     public class cat : animal
41     {
42         public override void eat()
43         {
44             console.writeline("猫也会吃东西");
45         }
46     }
47 
48     class program
49     {
50         static void main(string[] args)
51         {
52             //各种实现 体会吧
53             /*********************/
54             animal animal = new animal();
55             animal.eat();
56             dog dog = new dog();
57             dog.eat();
58             cat cat = new cat();
59             cat.eat();
60             /*******************/
61             console.writeline();
62             /********************/
63             animal[] al = new animal[3];
64             al[0] = new animal();
65             al[0].eat();
66             al[1] = new dog();
67             al[1].eat();
68             al[2] = new cat();
69             al[2].eat();
70             /*********************/
71             console.writeline();
72             /**********************/
73             animal a1 = new animal();
74             a1.eat();
75             animal a2 = new dog();
76             a2.eat();
77             animal a3 = new cat();
78             a3.eat();
79 
80             console.readkey();
81         }
82     }
83 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //下面是抽象类的多态:
 7 namespace _2.多态_抽象_
 8 {
 9     public abstract class animal
10     {
11         public abstract void eat();//请注意抽象方法没有方法体       
12     }
13 
14     public abstract class person:animal
15     {
16         public abstract void 喝拉撒睡();
17     }
18 
19     public class me : person
20     {
21         public override void eat()
22         {
23             console.writeline("我会吃");
24         }
25         //两个抽象方法缺一不可,要全部实现
26         public override void 喝拉撒睡()
27         {
28             console.writeline("我还会喝拉撒睡");
29         }
30     }
31 
32     public class you : animal   //you继承animal 继承用:
33     {
34         public override void eat()
35         {
36             console.writeline("你就是个吃货");
37         }
38     }
39 
40     class program
41     {
42         static void main(string[] args)
43         {
44             //animal animal = new animal();//抽象类不能被继承!!!!
45             me m = new me();
46             m.eat();
47             m.喝拉撒睡();
48             you y = new you();
49             y.eat();
50             ////////////
51             console.writeline();
52             ////////////
53             person[] p = new person[1];
54             animal[] a=new animal[2];
55             a[0] = new me();
56             p[0]= new me();
57             p[0].eat();
58             p[0].喝拉撒睡();           
59             
60             a[1] = new you();
61             a[1].eat();
62 
63             console.readkey();
64         }
65     }
66 }

  2.泛型

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 泛型方法
 7 {
 8     class program
 9     {
10         static void fx<t>(ref t l, ref t r)
11         {
12             //l和r值交换
13             t temp;
14             temp = l;
15             l = r;
16             r = temp;
17         }
18 
19         static void main(string[] args)
20         {
21             int a = 1;
22             int b = 2;
23 
24             //fx<int>(ref a, ref b);
25             fx(ref a, ref b);//这两种方式是一样的
26 
27             console.writeline(a+" "+b);
28             console.readkey();
29         }
30     }
31 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 泛型类
 7 {
 8     //我在这把通常大家爱写的t写成a,是为了让大家知道这知道代表一个类型不是固定的t
 9     class fxclass<a>
10     {
11        public void fx<a>(ref a l, ref a r)
12         {
13             a temp;
14             temp = l;
15             l = r;
16             r = temp;
17         }
18     }
19 
20     class program
21     {      
22         static void main(string[] args)
23         {
24             int a = 1;
25             int b = 2;
26 
27             fxclass<int> fxl = new fxclass<int>();
28             fxl.fx<int>(ref a, ref b);
29             console.writeline(a + " " + b);
30             console.readkey();
31         }
32     }
33 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 泛型接口
 7 {
 8     class program
 9     {
10         static void main(string[] args)
11         {
12             student stu = new student();
13             console.writeline(stu.jia(2, 3));
14             console.writeline(stu.jian(3, 1));
15             console.read();
16         }       
17     }
18 
19     //定义泛型接口
20     interface icomuter<t>
21     {
22         //定义泛型方法
23         t jia(t item1, t item2);
24         t jian(t item1, t item2);
25 
26     }
27 
28     //继承泛型接口
29     class student :  icomuter<int>
30     {
31         //继承实现泛型方法
32         public int jia(int item1, int item2)
33         {
34             return item1 + item2;
35         }
36         public int jian(int item1, int item2)
37         {
38             return item1 - item2;
39         }
40     }
41 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 #region .net泛型约束:
 7             //所谓泛型,即通过参数化类型来实现在同一份代码上操作多种数据类型。
 8 //泛型编程是一种编程范式,它利用“参数化类型”将类型抽象化,从而实现更为灵活的复用。
 9 
10 //在定义泛型类时,可以对客户端代码能够在实例化类时用于类型参数的类型种类施加限制。
11 //如果客户端代码尝试使用某个约束所不允许的类型来实例化类,则会产生编译时错误。
12             //这些限制称为约束。约束是使用 where 上下文关键字指定的。
13             #endregion
14 
15 #region 约束    说明
16 //t:struct
17 //类型参数必须是值类型。可以指定除 nullable 以外的任何值类型。
18 //t:class
19 //类型参数必须是引用类型,包括任何类、接口、委托或数组类型。
20 //t:new()
21 //类型参数必须具有无参数的公共构造函数。当与其他约束一起使用时,new() 约束必须最后指定。
22 //t:<基类名>
23 //类型参数必须是指定的基类或派生自指定的基类。
24 //t:<接口名称>
25 //类型参数必须是指定的接口或实现指定的接口。可以指定多个接口约束。约束接口也可以是泛型的。
26 //t:u
27 //为 t 提供的类型参数必须是为 u 提供的参数或派生自为 u 提供的参数。这称为裸类型约束.
28             #endregion
29 
30 namespace 泛型约束
31 {
32     class program
33     {
34         static void fx<t>(ref t l, ref t r) where t : icomparable //where是约束t类型在icomparable范围内
35         {
36             t temp;
37             temp = l;
38             l = r;
39             r = temp;
40         }
41 
42         static void main(string[] args)
43         {
44             int a = 1;
45             int b = 2;
46 
47             //fx<int>(ref a, ref b);
48             fx(ref a, ref b);//这两种方式是一样的
49             console.writeline(a + " " + b);
50             console.readkey();
51         }
52     }
53 }

  3.集合

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //泛型集合 很简单 我就介绍一下几个部分
 7 namespace _1.泛型集合_list_
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             list<int> list = new list<int>();
14             list.add(1);
15             list.add(2);
16             list.add(3);
17 
18             list.addrange(new int[]{4,5,6});//添加集合
19 
20             list.addrange(list);//添加自己
21 
22             int[] ii = list.toarray();//转为数组
23 
24             //怕误会以为泛型集合只可以操作整数
25             list<string> lt = new list<string>();
26             //其实都是一样的,我就不多写了
27             lt.add("请叫我:毕小帅");//大家都叫我“小帅”嘿嘿
28             lt.add("我叫:小毕");
29 
30             //输出
31             for (int i = 0; i < list.count; i++)
32             {
33                 console.write(list[i].tostring());
34             }
35             console.writeline();
36             for (int i = 0; i < lt.count; i++)
37             {
38                 console.writeline(lt[i].tostring());
39             }
40             console.writeline();
41             //也可以用foreach
42             //foreach在数据多的时候能比for的速度快
43             foreach (var item in list)
44             {
45                 console.write(item.tostring());
46             }
47 
48             console.readkey();
49         }
50     }
51 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.collections;
 6 
 7 namespace arraylist集合
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             arraylist al = new arraylist();
14             //我喜欢它的最重要的一点就是:他什么类型都可以储存
15             //还不用像数组一样定义长度
16             //和list集合不同的就是不用定义类型
17             //缺点 读取时需要拆装箱
18             al.add(1);          //添加数字
19             al.add("abc");      //添加字符串
20             al.add('d');        //添加字符
21 
22             al.addrange(new char[] { 'e', 'f' });//添加数组
23             al.addrange(al);    //添加集合 自己
24 
25             for (int i = 0; i < al.count; i++)
26             {
27                 console.writeline(al[i].tostring());
28             }
29 
30             console.read();
31         }
32     }
33 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace dictionary键值对集合
 7 {
 8     class program
 9     {
10         static void main(string[] args)
11         {
12             //他和list集合性质差不多,先确定了类型
13             dictionary<string, string> dy = new dictionary<string, string>();
14             
15             dy.add("key1", "value1");//添加
16 
17             dy["key2"] = "value2";//如果键不存在也可以通过此方法来添加键/值对
18 
19             dy.containskey("key1"); //判断该键是否存在
20 
21             foreach (object key in dy.keys) //遍历key
22             { }
23             foreach (object value in dy.values)//遍历value
24             { }
25 
26             foreach (var de in dy) //同时遍历键/值对
27             {
28                 console.writeline(de.key);
29                 console.writeline(de.value);
30             }
31             dy.clear();//清除所有
32 
33             console.read();
34         }
35     }
36 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.collections;
 6 
 7 namespace hashtable键值对集合
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             //我的感觉他和arrylist集合性质差不多,不分类型的存储
14             //键值是唯一的
15             hashtable ht = new hashtable();
16 
17             ht.add("key1", "value1");
18 
19             ht.add("key2", "value2");
20 
21             ht.contains("key1");//判断key1键是否存在
22 
23             ht.containskey("key1");//同上
24 
25             foreach (object key in ht.keys) //遍历key
26             { }
27             foreach (object value in ht.values)//遍历value
28             { }
29 
30             foreach (dictionaryentry de in ht) //同时遍历键/值对
31             {
32                 console.writeline(de.key);
33                 console.writeline(de.value);
34             }
35 
36 
37             /****************************/
38             ht.remove("key1");//移除key1键元素
39             
40             //前后做个判断
41             console.writeline();
42             foreach (dictionaryentry de in ht) //同时遍历键/值对
43             {
44                 console.writeline(de.key);
45                 console.writeline(de.value);
46             }
47             /********************************/
48 
49 
50 
51             /****************************/
52             ht.clear();//清除所有元素
53             
54             //前后做个判断
55             console.writeline();
56             foreach (dictionaryentry de in ht) //同时遍历键/值对
57             {
58                 console.writeline(de.key);
59                 console.writeline(de.value);
60                 console.writeline("这句话没输出就是键值对被清空了");
61             }
62 
63 
64             console.read();
65         }
66     }
67 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 枚举
 7 {
 8     class program
 9     {
10         static void main(string[] args)
11         {
12             console.writeline(enum.getname(typeof(man), 1));  //还是 刘备 (由值获取名字)
13 
14             string[] array1 = enum.getnames(typeof(man));
15             console.writeline(array1[1]);   //关羽
16 
17             array array2 = enum.getvalues(typeof(man));
18             console.writeline(array2.getvalue(1));  //还是关羽
19 
20             type t = enum.getunderlyingtype(typeof(man));
21             console.writeline(t);       //输出 int32
22 
23             //由值获取内容
24             int i = 1;
25             string name = enum.parse(typeof(man), i.tostring()).tostring();     //此时 name="刘备"
26             console.writeline(name);
27 
28             //由值获取内容
29             string name2 = "关羽";
30             int j = convert.toint32(enum.parse(typeof(man), name2));     //此时 j=2
31             console.writeline(j);
32 
33             //这段是我自己写的。。。。(不是全都复制的)
34             //判断输入的字符串是否在枚举内
35             console.writeline("请输入");
36             string str = console.readline();
37             bool b = enum.isdefined(typeof(week), str);
38 
39             console.writeline(b.tostring());
40 
41             console.readkey();
42         }
43     }
44 
45     enum man
46     {
47         刘备 = 1,
48         关羽 = 2,
49         张飞 = 3
50     }
51     enum week
52     {
53         monday = 1,
54         tuesday = 2,
55         wednesday = 3,
56         sunday = 0,
57         everyday = 1  //成员的值可以设置成一样的,但是成员不行
58     }
59     enum sex : byte  //显示指定枚举的底层数据类型
60     {
61         male,
62         female,  //此逗号可以省略
63     };        //此分号可以省略
64 
65 }

4.拆装箱

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.collections;
 6 using system.diagnostics;
 7 
 8 //装箱操作和拆箱操作是要额外耗费cpu和内存资源的,
 9 //所以用泛型来减少装箱操作和拆箱操作消耗。
10 namespace 拆箱_装箱
11 {
12     class program
13     {
14         static void main(string[] args)
15         {
16             int n1 = 10;
17             object o = n1;//装箱
18             int nn = (int)o;//拆箱
19 
20 
21             arraylist lista = new arraylist();
22             list<int> list = new list<int>();
23             //这个循环发生了100万次装箱操作
24             stopwatch sw = new stopwatch();
25             sw.start();
26             for (int i = 0; i < 10000000; i++)
27             {
28                 list.add(i);
29             }
30             sw.stop();//计时
31             console.writeline(sw.elapsed);
32             console.readkey();
33 
34 
35             //这个地方没有发生任意类型的装箱或者拆箱
36             string str = "123";
37             int n2 = convert.toint32(str);
38 
39 
40             int n3 = 10;
41             icomparable ic = n3;//装箱
42 
43         }
44     }
45 }

 5.逆变和协变

 1 在网上收集的,平时感觉不常用
 2 我们都知道.net里或者说在oo的世界里,可以安全地把子类的引用赋给父类引用,例如:
 3 
 4 //父类 = 子类
 5 string str = "string";
 6 object obj = str;//变了
 7 
 8 out 支持协变
 9 in  支持逆变
10 
11 协变(foo<父类> = foo<子类> ):  (个人理解:object(范围大)=string(范围小))
12 
13 //泛型委托:
14 public delegate t myfunca<t>();//不支持逆变与协变
15 public delegate t myfuncb<out t>();//支持协变
16  
17 myfunca<object> funcaobject = null;
18 myfunca<string> funcastring = null;
19 myfuncb<object> funcbobject = null;
20 myfuncb<string> funcbstring = null;
21 myfuncb<int> funcbint = null;
22  
23 funcaobject = funcastring;//编译失败,myfunca不支持逆变与协变
24 funcbobject = funcbstring;//变了,协变
25 funcbobject = funcbint;//编译失败,值类型不参与协变或逆变
26  
27 //泛型接口
28 public interface iflya<t> { }//不支持逆变与协变
29 public interface iflyb<out t> { }//支持协变
30  
31 iflya<object> flyaobject = null;
32 iflya<string> flyastring = null;
33 iflyb<object> flybobject = null;
34 iflyb<string> flybstring = null;
35 iflyb<int> flybint = null;
36  
37 flyaobject = flyastring;//编译失败,iflya不支持逆变与协变
38 flybobject = flybstring;//变了,协变
39 flybobject = flybint;//编译失败,值类型不参与协变或逆变
40  
41 //数组:
42 string[] strings = new string[] { "string" };
43 object[] objects = strings;
44 
45 ----------------------------------------------------------------------------------
46 
47 逆变(foo<子类> = foo<父类>)(个人理解:string(小范围)=object(大范围))
48 
49 public delegate void myactiona<t>(t param);//不支持逆变与协变
50 public delegate void myactionb<in t>(t param);//支持逆变
51  
52 public interface iplaya<t> { }//不支持逆变与协变
53 public interface iplayb<in t> { }//支持逆变
54  
55 myactiona<object> actionaobject = null;
56 myactiona<string> actionastring = null;
57 myactionb<object> actionbobject = null;
58 myactionb<string> actionbstring = null;
59 actionastring = actionaobject;//myactiona不支持逆变与协变,编译失败
60 actionbstring = actionbobject;//变了,逆变
61  
62 iplaya<object> playaobject = null;
63 iplaya<string> playastring = null;
64 iplayb<object> playbobject = null;
65 iplayb<string> playbstring = null;
66 playastring = playaobject;//iplaya不支持逆变与协变,编译失败
67 playbstring = playbobject;//变了,逆变

 6.工厂模式

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //个人理解:工厂模式就是switch选择为核心,让用户自己选择要执行的方法(但是方法他是看不见的)
 7 namespace 工厂模式
 8 {
 9     //第一步:先写抽象的父类
10     public abstract class all
11     {
12         public abstract void 上菜();
13     }
14     //第二步:子类 重写父类方法
15     public class gdfjdc : all
16     {
17         public override void 上菜()
18         {
19             console.writeline("小二,上干豆腐卷大葱");//我是东北人
20         }
21     }
22     public class xcbdf : all
23     {
24         public override void 上菜()
25         {
26             console.writeline("小二上小葱拌豆腐");
27         }
28     }
29     public class xjdmg : all
30     {
31         public override void 上菜()
32         {
33             console.writeline("小二上小鸡炖蘑菇");
34         }
35     }
36     public class scy : all
37     {
38         public override void 上菜()
39         {
40             console.writeline("小二上酸菜鱼");
41         }
42     }
43     
44     class class1
45     {
46         //第三步:核心地方到了 switch选择
47         public static all getuserstr(string str_user)
48         {
49             all db = null;
50             switch (str_user)
51             {
52                 case "干豆腐卷大葱": db = new gdfjdc();
53                     break;
54                 case "小葱拌豆腐": db = new xcbdf();
55                     break;
56                 case "小鸡炖蘑菇": db = new xjdmg();
57                     break;
58                 case "酸菜鱼": db = new scy();
59                     break;
60             }
61             return db;
62         }
63         static void main()
64         {
65             //开始用户选菜了
66             string str_user = console.readline();
67             all db = getuserstr(str_user);
68             db.上菜();
69 
70             console.read();
71         }
72     }
73 }

 7.部分类partial

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 部分类partial
 7 {
 8     partial class program
 9     {
10         static void main(string[] args)
11         {
12             print();
13             console.readkey();
14         }
15     }
16     partial class program
17     {
18        static string str = "我是大帅哥";
19     }
20 
21     partial class program
22     {
23         public static void print()
24         {
25             console.writeline(str);
26         }
27     }
28 }

 8.密封类sealed

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 密封类
 7 {
 8     class program
 9     {
10         static void main(string[] args)
11         {
12             person.person();
13             test.test();
14 
15             console.read();
16         }
17     }
18     //密封类用sealed关键字
19    // public static sealed class person : test//这是错误的!!类不能即是密封的又是静态static的
20     public sealed class person : test
21     {
22         public static void person()
23         {
24             console.writeline("我是密封类");
25         }
26     }
27     //public static class test //这是错误的!!密封类不能继承于静态类
28     public class test
29     {
30         public static void test()
31         {
32             console.writeline("我是父类");
33         }
34     }
35     //public class abc : person { }//这是错误的!!密封类不能被继承
36 }

 9.重写tostring方法

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //首先要知道tostring是系统内部自有的方法
 7 //系统内定义:public override string tostring(); 是个可被重写的方法
 8 //这个例子不是简单的说明重写tostring,说明有很多系统定义的方法,我们都可以拿来重写的
 9 namespace 重写tostring方法
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             person p = new person();
16             console.writeline(p.tostring());
17             console.readkey(); 
18         }
19     }
20 
21     public class person
22     {
23         public override string tostring()
24         {
25             return "hello world";
26         }
27     }
28 }

10.属性

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //看网上对属性的讲解:
 7 //c#中为什么要用属性,1、在给一个对象附值时,可以通过属性set方法,
 8 //对这个值进行一个过滤,看这个值服不服合属性的要求。2、有的对象的属性,
 9 //需要只读的的,就可以省去set方法,有的是只写的,就可以省去get方法
10 
11 //属性就是为了访问私有字段,也就是为了对私有字段进行封装
12 
13 //公有属性是在任何外部类都可访问到的,如果有人不怀好意就会随意的修改的public字段,
14 //很危险的,但是如果改成private,就不能擅自修改,只能通过属性,而在属性里是可以
15 //加代码来判断别人付的值是否符合你的要求,不符合的可以直接拒绝赋值,这样就增加了安全性
16 namespace 属性
17 {
18     class program
19     {
20         /// <summary>
21         /// 自动属性
22         /// </summary>
23         public int age
24         {
25             get;
26             set;
27         }
28 
29         //普通属性
30         private string _name;
31 
32         public string name
33         {
34             get { return _name; }
35             set { _name = value; }
36         }
37 
38         static void main(string[] args)
39         {
40         }
41     }        
42 }

11.里氏转换is、as

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 //里氏转换
 6 //1、子类可以复制给父类:如果有一个地方需要一个父类做参数,我们可以给一个子类代替
 7 //2、如果父类中装的是子类对象,那么我们是可以将这个父类转换为子类对象的
 8 
 9 namespace is_as
10 {
11     public class user
12     {
13 
14     }
15     class program
16     {
17         static void main(string[] args)
18         {
19             object obj1 = new user();
20             //is:表示类型转换----如果转换成功,返回一个true,否则返回false
21             if (obj1 is user)//这里一定要知道object是一切类的父类,父类转子类判断是否成功
22             {
23                 user user1 = (user)obj1;//将父类对象强制转换成子类对象
24                 console.writeline("转换成功");
25             }
26             else
27             {
28                 console.writeline("转换失败");
29             }
30 
31             /****************************/
32 
33             object obj2 = new user();
34             //as:表示类型转换-----如果能够转换则返回一个对应的对象,否则返回一个null
35             user user2 = obj2 as user;//将父类对象强制转换成子类对象
36             if (user2 == null)
37             {
38                 console.writeline("转换失败");
39             }
40             else
41             {
42                 console.writeline("转换成功");
43             }
44             console.readkey();
45         }
46     }
47 }

 12.接口

别人写的,注释写的很好,简单易懂

  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 
  6 #region 介绍接口
  7 //如要实现接口类中对应的成员必须是公共的、非静态的,
  8 //并且与接口成员具有相同的名称和签名。
  9 //并且接口的实例化不能像类那样program program = new program();
 10 //其中上述程序中红色部分即为接口的实例化(使用派生类对象实例化接口)。
 11 //1、接口的概念及声明
 12 
 13 //接口是一种用来定义程序的协议,它描述可属于任何类或结构的一组相关行为。接口可有方法、属性、事件和索引器或这四种成员的任何组合类型,但不能包含字段。
 14 
 15 //那么接口具有哪些特点呢?
 16 
 17 //·接口类似于抽象基类:继承接口的任何非抽象类型都必须实现接口的所有成员(说明:如类a继承接口b,那么a中必须实现b中定义的属性,方法等)。
 18 
 19 //·不能直接实例化接口
 20 
 21 //·接口可以包含事件、索引器、方法和属性
 22 
 23 //·接口不包含方法的实现
 24 
 25 //·类和接口可以从多个接口继承
 26 
 27 //·接口自身可以继承多个接口
 28 
 29 //在声明接口时除了interface和接口名称是必须的,其他都是可选项。另可使用new、public、protected、intenal和private等修饰符实现接口,但接口成员必须是公共的。
 30 
 31 //2、接口的实现与继承
 32 
 33 //声明实现接口的类时,需要在基类列表中包含类所实现的接口的名称。
 34 #endregion
 35 namespace 接口_单继承_
 36 {
 37     interface imyinterface
 38     {
 39         /// <summary>
 40         /// 编号(可读可写)
 41         /// </summary>
 42         string id
 43         {
 44             get;
 45             set;
 46         }
 47         /// <summary>
 48         /// 姓名(可读可写)
 49         /// </summary>
 50         string name
 51         {
 52             get;
 53             set;
 54         }
 55         /// <summary>
 56         /// 显示定义的编号和姓名
 57         /// </summary>
 58         void showinfo();
 59     }
 60     class program : imyinterface//继承自接口
 61     {
 62         string id = "";
 63         string name = "";
 64         /// <summary>
 65         /// 编号
 66         /// </summary>
 67         public string id
 68         {
 69             get
 70             {
 71                 return id;
 72             }
 73             set
 74             {
 75                 id = value;
 76             }
 77         }
 78         /// <summary>
 79         /// 姓名
 80         /// </summary>
 81         public string name
 82         {
 83             get
 84             {
 85                 return name;
 86             }
 87             set
 88             {
 89                 name = value;
 90             }
 91         }
 92         /// <summary>
 93         /// 显示定义的编号和姓名
 94         /// </summary>
 95         public void showinfo()
 96         {
 97             console.writeline("编号\t 姓名");
 98             console.writeline(id + "\t " + name);
 99         }
100         static void main(string[] args)
101         {
102             program program = new program();               //实例化program类对象
103             imyinterface imyinterface = program;           //使用派生类对象实例化接口imyinterface
104             imyinterface.id = "tm";                        //为派生类中的id属性赋值
105             imyinterface.name = "c# 2.0从入门到应用开发";  //为派生类中的name属性赋值
106             imyinterface.showinfo();                       //调用派生类中方法显示定义的属性值
107             console.readkey();
108         }
109     }
110 }
  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 
  6 namespace 多继承
  7 {
  8     interface ipeople
  9     {
 10         /// <summary>
 11         /// 姓名
 12         /// </summary>
 13         string name
 14         {
 15             get;
 16             set;
 17         }
 18         /// <summary>
 19         /// 性别
 20         /// </summary>
 21         string sex
 22         {
 23             get;
 24             set;
 25         }
 26     }
 27     interface iteacher : ipeople            //继承公共接口
 28     {
 29         /// <summary>
 30         /// 教学方法
 31         /// </summary>
 32         void teach();
 33     }
 34     interface istudent : ipeople            //继承公共接口
 35     {
 36         /// <summary>
 37         /// 学习方法
 38         /// </summary>
 39         void study();
 40     }
 41     class program : ipeople, iteacher, istudent//多接口继承
 42     {
 43         string name = "";
 44         string sex = "";
 45         /// <summary>
 46         /// 姓名
 47         /// </summary>
 48         public string name
 49         {
 50             get
 51             {
 52                 return name;
 53             }
 54             set
 55             {
 56                 name = value;
 57             }
 58         }
 59         /// <summary>
 60         /// 性别
 61         /// </summary>
 62         public string sex
 63         {
 64             get
 65             {
 66                 return sex;
 67             }
 68             set
 69             {
 70                 sex = value;
 71             }
 72         }
 73         /// <summary>
 74         /// 教学方法
 75         /// </summary>
 76         public void teach()
 77         {
 78             console.writeline(name + " " + sex + " 教师");
 79         }
 80         /// <summary>
 81         /// 学习方法
 82         /// </summary>
 83         public void study()
 84         {
 85             console.writeline(name + " " + sex + " 学生");
 86         }
 87         static void main(string[] args)
 88         {
 89             program program = new program();   //实例化类对象
 90             iteacher iteacher = program;       //使用派生类对象实例化接口iteacher
 91             iteacher.name = "tm";
 92             iteacher.sex = "男";
 93             iteacher.teach();
 94             istudent istudent = program;       //使用派生类对象实例化接口istudent
 95             istudent.name = "c#";
 96             istudent.sex = "男";
 97             istudent.study();
 98             console.readkey();
 99         }
100     }
101 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 #region
 7 //试想一下,如果在一个类a继承自接口b和c,
 8 //并且在b和c中包含具有相同签名的成员,
 9 //那么在类中实现该成员将导致两个接口都使用该成员作为他们的实现,
10 //然而,如果两个接口成员实现不同的功能,
11 //那么将会导致一个接口的成员实现不正确或两个接口的成员实现都不正确,
12 //这个时候我们应该如何处理呢?我们可以显示的实现接口成员,
13 //即创建一个仅通过接口调用并且特定于该接口的类成员。
14 #endregion
15 namespace 显示实现接口成员
16 {
17     interface imyinterface1
18     {
19         /// <summary>
20         /// 求和方法
21         /// </summary>
22         /// <returns>加法运算的和</returns>
23         int add();
24     }
25     interface imyinterface2
26     {
27         /// <summary>
28         /// 求和方法
29         /// </summary>
30         /// <returns>加法运算的和</returns>
31         int add();
32     }
33     class myclass : imyinterface1, imyinterface2    //继承接口
34     {
35         /// <summary>
36         /// 求和方法
37         /// </summary>
38         /// <returns>加法运算的和</returns>
39         int imyinterface1.add()                     //显式接口成员实现
40         {
41             int x = 3;
42             int y = 5;
43             return x + y;
44         }
45         /// <summary>
46         /// 求和方法
47         /// </summary>
48         /// <returns>加法运算的和</returns>
49         int imyinterface2.add()                      //显式接口成员实现
50         {
51             int x = 3;
52             int y = 5;
53             int z = 7;
54             return x + y + z;
55         }
56     }
57     class program
58     {
59         static void main(string[] args)
60         {
61             myclass myclass = new myclass();          //实例化接口继承类的对象
62             imyinterface1 imyinterface1 = myclass;    //使用接口继承类的对象实例化接口
63             console.writeline(imyinterface1.add());   //使用接口对象调用接口中方法
64             imyinterface2 imyinterface2 = myclass;    //使用接口继承类的对象实例化接口
65             console.writeline(imyinterface2.add());   //使用接口对象调用接口中方法
66             console.readkey();
67         }
68     }
69 }
70 //上面的实例中在myclass类中,通过两个显示接口成员的方法分别实现了两个接口中的add方法,在实例化不同的接口后,调用相应的方法实现输出结果。

13.接口与抽象类的区别

 1 c#接口和抽象类的区别 
 2 
 3  大家都容易把这两者搞混,我也一样,在听李建忠老师的设计模式时,他也老把抽象类说成接口,弄的我就更糊涂了,所以找了些网上的资料.
 4       一、抽象类:
 5       抽象类是特殊的类,只是不能被实例化;除此以外,具有类的其他特性;重要的是抽象类可以包括抽象方法,这是普通类所不能的。抽象方法只能声明于抽象类中,且不包含任何实现,派生类必须覆盖它们。另外,抽象类可以派生自一个抽象类,可以覆盖基类的抽象方法也可以不覆盖,如果不覆盖,则其派生类必须覆盖它们。
 6 
 7 
 8        二、接口:
 9       接口是引用类型的,类似于类,和抽象类的相似之处有三点:
10        1、不能实例化;
11        2、包含未实现的方法声明;
12        3、派生类必须实现未实现的方法,抽象类是抽象方法,接口则是所有成员(不仅是方法包括其他成员);
13 
14        另外,接口有如下特性:
15 接口除了可以包含方法之外,还可以包含属性、索引器、事件,而且这些成员都被定义为公有的。除此之外,不能包含任何其他的成员,例如:常量、域、构造函数、析构函数、静态成员。一个类可以直接继承多个接口,但只能直接继承一个类(包括抽象类)。
16 
17       三、抽象类和接口的区别:
18       1.类是对对象的抽象,可以把抽象类理解为把类当作对象,抽象成的类叫做抽象类.而接口只是一个行为的规范或规定,微软的自定义接口总是后带able字段,证明其是表述一类类“我能做。。。”.抽象类更多的是定义在一系列紧密相关的类间,而接口大多数是关系疏松但都实现某一功能的类中. 
19       2.接口基本上不具备继承的任何具体特点,它仅仅承诺了能够调用的方法;     
20       3.一个类一次可以实现若干个接口,但是只能扩展一个父类     
21       4.接口可以用于支持回调,而继承并不具备这个特点.     
22       5.抽象类不能被密封。   
23       6.抽象类实现的具体方法默认为虚的,但实现接口的类中的接口方法却默认为非虚的,当然您也可以声明为虚的. 
24       7.(接口)与非抽象类类似,抽象类也必须为在该类的基类列表中列出的接口的所有成员提供它自己的实现。但是,允许抽象类将接口方法映射到抽象方法上。   
25       8.抽象类实现了oop中的一个原则,把可变的与不可变的分离。抽象类和接口就是定义为不可变的,而把可变的座位子类去实现。   
26       9.好的接口定义应该是具有专一功能性的,而不是多功能的,否则造成接口污染。如果一个类只是实现了这个接口的中一个功能,而不得不去实现接口中的其他方法,就叫接口污染。   
27      10.尽量避免使用继承来实现组建功能,而是使用黑箱复用,即对象组合。因为继承的层次增多,造成最直接的后果就是当你调用这个类群中某一类,就必须把他们全部加载到栈中!后果可想而知.(结合堆栈原理理解)。同时,有心的朋友可以留意到微软在构建一个类时,很多时候用到了对象组合的方法。比如asp.net中,page类,有server request等属性,但其实他们都是某个类的对象。使用page类的这个对象来调用另外的类的方法和属性,这个是非常基本的一个设计原则。   
28      11.如果抽象类实现接口,则可以把接口中方法映射到抽象类中作为抽象方法而不必实现,而在抽象类的子类中实现接口中方法.
29    
30       四、抽象类和接口的使用:
31       1. 如果预计要创建组件的多个版本,则创建抽象类。抽象类提供简单的方法来控制组件版本。
32       2.如果创建的功能将在大范围的全异对象间使用,则使用接口。如果要设计小而简练的功能块,则使用接口。
33       3.如果要设计大的功能单元,则使用抽象类.如果要在组件的所有实现间提供通用的已实现功能,则使用抽象类。   
34       4.抽象类主要用于关系密切的对象;而接口适合为不相关的类提供通用功能。
35 
36  以下是我在网上看到的几个形象比喻,真的非常不错,呵呵:
37 1.飞机会飞,鸟会飞,他们都继承了同一个接口“飞”;但是f22属于飞机抽象类,鸽子属于鸟抽象类。
38 2. 就像铁门木门都是门(抽象类),你想要个门我给不了(不能实例化),但我可以给你个具体的铁门或木门(多态);而且只能是门,你不能说它是窗(单继承);一个门可以有锁(接口)也可以有门铃(多实现)。 门(抽象类)定义了你是什么,接口(锁)规定了你能做什么(一个接口最好只能做一件事,你不能要求锁也能发出声音吧(接口污染))。

 14.流操作

 1 个人简单理解:
 2 filestream   操作字节的            
 3 streamreader和streamwriter 操作字符的
 4 
 5 网络上的解释:
 6 1. filestream是一个较为底层的类,只能简单地读文件到缓存区,而streamreader封装了一些高级方法如readline()
 7 2. filestream可读可写,而streamreader只能读不能写
 8 3. filestream不能指定编码(因为它看到的只是文件的二进制形式,当然无所谓编码),而streamreader可以指定编码,一旦指定就不允许再更改,因此编码指定是放在它的构造方法里的。默认编码为system.text.utf8encoding,实际上,在streamreader的构造方法里,它会对文件进行编码检查,当然也可以不让它检查。
 9 4. 若对是对二进制文件进行操作,最好使用binaryreader,若要进行写操作,则用streamwriter,同样streamwriter也能按指定的编码进行读写
10 5. streamreader的构造方法不一定需要filestream,只需要文件名即可
11 6. streamreader关闭后,与之相关的filestream没有关闭,(通过filestream的canread的测试)
12 
13 filestream对象表示在磁盘或网络路径上指向文件的流。这个类提供了在文件中读写字节的方法,
14 但经常使用streamreader或streamwriter执行这些功能。这是因为filestream类操作的是字节和
15 字节数组,而stream类操作的是字符数据。这是这两种类的一个重要区别,如果你是准备读取byte
16 数据的话,用streamreader读取然后用system.text.encoding.default.getbytes转化的话,如下,
17 则可能出现数据丢失的情况,如byte数据的个数不对等。因此操作byte数据时要用filestream。
18  
19 string textcontent = filestream.readtoend();byte[] bytes = system.text.encoding.default.getbytes(textcontent); 
20 字符数据易于使用,但是有些操作,比如随机文件访问(访问文件中间某点的数据),就必须由filestream对象执行.
21 其中创建filestream对象最简单的构造函数如下: 
22 1filestream file = newfilestream(filename,filemode.member); 
23 2filestream file = newfilestream(filename, filemode.member, fileaccess.member);
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 
 7 namespace _streamreader
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             //使用streamreader来读取一个文本文件
14             //首先在\bin\debug目录里(也就是程序运行的当前目录里要有new.txt文件),否则报错
15             using (streamreader sr = new streamreader(@"new.txt", encoding.utf8))//utf8是一种读取的格式,还有其他很多种格式
16             {
17                 while (!sr.endofstream)
18                 {
19                     console.writeline(sr.readline());
20                 }
21             }
22             console.readkey();
23         }
24     }
25 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 //filestream   操作字节的            
 7 //streamreader和streamwriter 操作字符的
 8 namespace _streamwriter
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             //使用streamwriter来写入一个文本文件
15             //首先在\bin\debug目录里(也就是程序运行的当前目录里要有new.txt文件),否则报错
16             using (streamwriter sw = new streamwriter(@"new.txt", true))
17             {
18                 sw.write("看我有木有把你覆盖掉");
19             }
20             console.writeline("ok");
21             console.readkey();
22         }
23     }
24 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 
 7 namespace 文件流
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             //使用filestream来读取数据
14             filestream fsread = new filestream(@"bxs.txt", filemode.openorcreate, fileaccess.read);
15             byte[] buffer = new byte[1024 * 1024 * 5];
16             //2.84k  5m
17             //返回本次实际读取到的有效字节数
18             int r = fsread.read(buffer, 0, buffer.length);
19             //将字节数组中每一个元素按照指定的编码格式解码成字符串
20             string s = encoding.default.getstring(buffer, 0, r);
21             //关闭流
22             fsread.close();
23             //释放流所占用的资源 可以使用using替代它
24             fsread.dispose();
25             console.writeline(s);
26             console.readkey();
27         }
28     }
29 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 
 7 namespace 写入文件
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             //使用filestream来写入数据
14             using (filestream fswrite = new filestream(@"new.txt", filemode.openorcreate, fileaccess.write))
15             {
16                 string str = "看我有没有把你覆盖掉";
17                 byte[] buffer = encoding.utf8.getbytes(str);
18                 fswrite.write(buffer, 0, buffer.length);
19             }
20             console.writeline("写入ok");
21             console.readkey();
22         }
23     }
24 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 
 7 namespace 文件流拷贝多媒体文件
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             //思路:就是先将要复制的多媒体文件读取出来,然后再写入到你指定的位置
14             string source = @"abc.wmv";
15             string target = @"new.wmv";
16             copyfile(source, target);
17             console.writeline("复制成功");
18             console.readkey();
19         }
20 
21         public static void copyfile(string soucre, string target)
22         {
23             //1、我们创建一个负责读取的流
24             using (filestream fsread = new filestream(soucre, filemode.open, fileaccess.read))
25             {
26                 //2、创建一个负责写入的流
27                 using (filestream fswrite = new filestream(target, filemode.openorcreate, fileaccess.write))
28                 {
29                     byte[] buffer = new byte[1024 * 1024 * 5];
30                     //因为文件可能会比较大,所以我们在读取的时候 应该通过一个循环去读取
31                     while (true)
32                     {
33                         //返回本次读取实际读取到的字节数
34                         int r = fsread.read(buffer, 0, buffer.length);
35                         //如果返回一个0,也就意味什么都没有读取到,读取完了
36                         if (r == 0)
37                         {
38                             break;
39                         }
40                         fswrite.write(buffer, 0, r);
41                     }
42                 }
43             }
44         }
45     }
46 }

 15.序列化、反序列化(xml和二进制)

首先看一下我生成的xml文件,这里我就不讲解xml文件格式是怎么写的,很简单

 1 <?xml version="1.0"?>
 2 
 3 -<arrayofperson xmlns:xsd="http://www.w3.org/2001/xmlschema" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance">
 4 
 5 
 6 -<person>
 7 
 8 <name>毕毕</name>
 9 
10 <myproperty>23</myproperty>
11 
12 </person>
13 
14 
15 -<person>
16 
17 <name>丹丹</name>
18 
19 <myproperty>22</myproperty>
20 
21 </person>
22 
23 </arrayofperson>

 

 1 序列化又称串行化,是.net运行时环境用来支持用户定义类型的流化的机制。
 2 其目的是以某种存储形成使自定义对象持久化,或者将这种对象从一个地方传输到另一个地方。
 3 
 4 .net框架提供了两种种串行化的方式:
 5 1、是使用binaryformatter进行串行化;
 6 2、使用xmlserializer进行串行化。
 7 第一种方式提供了一个简单的二进制数据流以及某些附加的类型信息,
 8 而第二种将数据流格式化为xml存储。    
 9 可以使用[serializable]属性将类标志为可序列化的。如果某个类的元素不想被序列化,
10 1、可以使用[nonserialized]属性来标志,
11 2、可以使用[xmlignore]来标志。
12 
13 序列化意思指的是把对象的当前状态进行持久化,一个对象的状态在面向对象的程序中是由属性表示的,
14 所以序列化类的时候是从属性读取值以某种格式保存下来,而类的成员函数不会被序列化,
15 .net存在几种默认提供的序列化,二进制序列化,xml和json序列化会序列化所有的实例共有属性。
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 using system.xml.serialization;
 7 
 8 namespace xml序列化_反序列化
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             list<person> listpers = new list<person>();
15             person p1 = new person("毕毕", 23);
16             person p2 = new person("丹丹", 22);
17 
18             listpers.add(p1);
19             listpers.add(p2);//把类的实例添加到listpers泛型列表中
20 
21             xmlserializemethod(listpers);//序列化成xml       
22            // rexmlserializemethod();//反序列化
23 
24             console.read();
25         }
26 
27         //序列化一个泛型列表到xml
28         public static void xmlserializemethod(list<person> listpers)
29         {
30             using (filestream fs = new filestream("序列化.xml", filemode.openorcreate))
31             {
32                 xmlserializer xs = new xmlserializer(typeof(list<person>));
33                 xs.serialize(fs, listpers);
34 
35                 console.writeline("序列化.xml" + "序列化文件成功");
36             }
37         }
38         //反序列化一个xml到泛型列表
39         public static void rexmlserializemethod()
40         {
41             using (filestream fs = new filestream("序列化.xml", filemode.open))
42             {
43                 xmlserializer xs = new xmlserializer(typeof(list<person>));
44                 list<person> listpers = xs.deserialize(fs) as list<person>;
45                 if (listpers != null)
46                 {
47                     for (int i = 0; i < listpers.count; i++)
48                     {
49                         listpers[i].sayhi();
50                     }
51                 }
52 
53             }
54         }
55     }
56 
57     [serializable]// 表示要进行序列化
58     public class person
59     {
60         public person() { }
61         public person(string name, int age)
62         {
63             this.name = name;
64             this.age = age;
65         }
66         private string name;
67         public string name
68         {
69             get { return name; }
70             set { name = value; }
71         }
72         [nonserialized]//表示下面的age不进行序列化
73         private int age;
74 
75         public int myproperty
76         {
77             get { return age; }
78             set { age = value; }
79         }
80 
81         public void sayhi()
82         {
83             console.writeline("大家好,我是{0},今年{1}岁", name, age);
84         }
85 
86     }
87 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 using system.runtime.serialization.formatters.binary;
 7 
 8 //会生成.bin文件(二进制文件)
 9 namespace 二进制序列化_反序列化
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             list<person> listpers = new list<person>();
16             person per1 = new person("毕毕", 18);
17             person per2 = new person("丹丹", 20);
18             listpers.add(per1);
19             listpers.add(per2);
20 
21             serializemethod(listpers);//序列化
22             console.writeline("序列化完成");
23             
24             //reserializemethod();//反序列化,使用反序列化时把序列化部分注释,反序列化打开
25 
26             #region 输出
27             //输出: 因为age不被序列化,所以为0
28             //序列化完成
29             //大家好,我是毕毕,今年0岁
30             //大家好,我是丹丹,今年0岁
31             #endregion
32 
33             console.readkey();
34         }
35 
36         static void reserializemethod()
37         {
38             //反序列化
39             using (filestream fs = new filestream("二进制.bin", filemode.open))
40             {
41                 binaryformatter bf = new binaryformatter();
42                 list<person> list = bf.deserialize(fs) as list<person>;
43                 if (list != null)
44                 {
45                     for (int i = 0; i < list.count; i++)
46                     {
47                         list[i].sayhi();
48                     }
49                 }
50             }
51         }
52 
53         static void serializemethod(list<person> listpers)
54         {
55             //序列化
56             using (filestream fs = new filestream("二进制.bin", filemode.openorcreate))
57             {
58                 binaryformatter bf = new binaryformatter();
59                 bf.serialize(fs, listpers);
60             }
61         }
62 
63     }
64 
65     [serializable]// 表示要进行序列化
66     class person
67     {
68         public person(){}
69         public person(string name, int age)
70         {
71             this.name = name;
72             this.age = age;
73         }
74         private string name;
75         public string name
76         {
77             get { return name; }
78             set { name = value; }
79         }
80         [nonserialized]//表示下面的age不进行序列化
81         private int age;
82 
83         public int myproperty
84         {
85             get { return age; }
86             set { age = value; }
87         }
88 
89         public void sayhi()
90         {
91             console.writeline("大家好,我是{0},今年{1}岁",name,age);
92         }        
93     }
94 }

1 using system; 2 using system.collections.generic; 3 using system.linq; 4 using system.text; 5 6 //少量属性的自动化操作手动添加几下当然是没有问题的,但是属性数量较多的时候敲起 7 //这些繁锁的代码可以困了,再说对扩展和维护性造成很多的不便,这时,就需要使用反射来实现了。 8 9 //为了方便查看,建议使用计时窗口。也可以节点查看 10 11 //了解了类的属性反射使用后,那么方法也是可以这样做的, 12 //即t.getproperties()改为t.getmethods(),操作方法同上。 13 namespace 反射 14 { 15 public class a 16 { 17 public int property1 { get; set; } 18 } 19 class program 20 { 21 static void main() 22 { 23 a aa = new a(); 24 type type = aa.gettype();//获取类型 25 // string aaname = aa.name; //获取类型名 26 // string aafullname = aa.fullname; //获取命名空间 27 // type stu1 = typeof(student); 28 // type stu = type.gettype("反射.student"); 29 system.reflection.propertyinfo propertyinfo = type.getproperty("property1"); 30 propertyinfo.setvalue(aa, 5, null);//给对应属性赋值.可以改成循环赋值 31 int value = (int)propertyinfo.getvalue(aa, null); 32 console.writeline(value); 33 34 console.read(); 35 } 36 } 37 38 public class student 39 { 40 public void abc() 41 { 42 console.writeline("无所谓啦,反正不用输出的"); 43 } 44 } 45 }

16.propertyinfo反射

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //少量属性的自动化操作手动添加几下当然是没有问题的,但是属性数量较多的时候敲起
 7 //这些繁锁的代码可以困了,再说对扩展和维护性造成很多的不便,这时,就需要使用反射来实现了。
 8 
 9 //为了方便查看,建议使用计时窗口。也可以节点查看
10 
11 //了解了类的属性反射使用后,那么方法也是可以这样做的,
12 //即t.getproperties()改为t.getmethods(),操作方法同上。
13 namespace 反射
14 {
15     public class a
16     {
17         public int property1 { get; set; }
18     }
19     class program
20     {
21         static void main()
22         {
23             a aa = new a();
24             type type = aa.gettype();//获取类型
25             //    string aaname = aa.name;    //获取类型名
26             //    string aafullname = aa.fullname; //获取命名空间
27             //    type stu1 = typeof(student);
28             //    type stu = type.gettype("反射.student");
29             system.reflection.propertyinfo propertyinfo = type.getproperty("property1");
30             propertyinfo.setvalue(aa, 5, null);//给对应属性赋值.可以改成循环赋值
31             int value = (int)propertyinfo.getvalue(aa, null);
32             console.writeline(value);
33 
34             console.read();
35         }
36     }
37 
38     public class student
39     {
40         public void abc()
41         {
42             console.writeline("无所谓啦,反正不用输出的");
43         }
44     }
45 }

 17.guid编号

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //guid代码是不重复的编号
 7 //有时可以使用guid编号作为数据库的id值
 8 //买商品时收款机打印的编号就是利用的guid编号
 9 namespace _13.guid代码
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             //产生一个不会重复的编号
16             console.writeline(guid.newguid().tostring());
17             console.writeline(guid.newguid().tostring());
18             console.writeline(guid.newguid().tostring());
19             console.writeline(guid.newguid().tostring());
20             console.writeline(guid.newguid().tostring());
21             console.readkey();
22 
23             //这只是一次结果,每次都不一样的
24             //c2ad2105-28c3-48cc-a550-ec6ecce7deba
25             //18881ad6-0cb9-49a5-b1c2-4747ccb3111c
26             //26c63df2-63f9-4d5b-8648-c6fd19d08c19
27             //a6b02a41-af88-4fd9-8b80-d14b4ef423d9
28             //3d8e93cb-5982-4b6f-bf63-33489929963a
29         }
30     }
31 }

18.stringbuilder

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 
 7 //string 在进行运算时(如赋值、拼接等)会产生一个新的实例,
 8 //而 stringbuilder 则不会,stringbuilder会在内存中开辟一块
 9 //连续的内存,当增加字符串实际上是针对同一块内存的修改,所以效率更高。
10 //一字符串进行操作时最好使用 stringbuilder,不要使用 string
11 
12 namespace _14_高效的stringbuilder
13 {
14     class program
15     {
16         static void main(string[] args)
17         {
18             stringbuilder sb = new stringbuilder();
19             sb.append("张三");
20             sb.append("李四");
21             sb.append("王五");
22             sb.append("李四");
23             sb.insert(1, 123);
24             sb.replace("李四", "赵六");//把sb集合里的所有“李四”替换成赵六
25             sb.replace("赵六", "七七");
26             console.writeline(sb.tostring());
27             console.readkey();
28         }
29     }
30 }
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.threading.tasks;
 9 using system.windows.forms;
10 
11 //winform类型
12 namespace 使用stringbuilder来拼接网页
13 {
14     public partial class form1 : form
15     {
16         public form1()
17         {
18             initializecomponent();
19         }
20 
21         private void button1_click(object sender, eventargs e)
22         {
23 
24             stringbuilder sb = new stringbuilder();
25             sb.append("<html>");
26             sb.append("<head>");
27             sb.append("</head>");
28             sb.append("<body>");
29             sb.append("<table border='1px' cellpadding='0px' cellspacing='0px'>");
30             sb.append("<tr>");
31             sb.append("<td>星期一</td>");
32             sb.append("<td>星期一</td>");
33             sb.append("<td>星期一</td>");
34             sb.append("<td>星期一</td>");
35             sb.append("</tr>");
36             sb.append("<tr>");
37             sb.append("<td>星期一</td>");
38             sb.append("<td>星期一</td>");
39             sb.append("<td>星期一</td>");
40             sb.append("<td>星期一</td>");
41             sb.append("</tr>");
42             sb.append("<tr>");
43             sb.append("<td>星期一</td>");
44             sb.append("<td>星期一</td>");
45             sb.append("<td>星期一</td>");
46             sb.append("<td>星期一</td>");
47             sb.append("</tr>");
48             sb.append("<tr>");
49             sb.append("<td>星期一</td>");
50             sb.append("<td>星期一</td>");
51             sb.append("<td>星期一</td>");
52             sb.append("<td>星期一</td>");
53             sb.append("</tr>");
54             sb.append("</table>");
55             sb.append("</body>");
56             sb.append("</html>");
57             webbrowser1.documenttext = sb.tostring();//这是添加了一个窗体空间,显示网页数据的
58         }
59     }
60 }

 体现一下stringbuilder和string的差距,网上直接复制的一份对比程序

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.diagnostics;
 6 
 7 //string类型的特别之处在于我们可以像使用值类型那样使用string类型,
 8 //而实际上string是引用类型。既然是引用类型,clr就会把string类型保
 9 //存在托管堆上。当我们使用str1 = str1 + i.tostring();进行拼接,由
10 //于string类型的恒定性,不会改变str1在内存中的地址,而是在托管堆上
11 //创建了另外一个字符串对象。如此,拼接10000次,就创建了10000个string
12 //类型对象,效率难免低下。
13 
14 //而stringbuilder会在内存中开辟一块连续的内存,当增加字符串实际上是
15 //针对同一块内存的修改,所以效率更高。 
16 
17 //当然,到底使用硬拼接字符串,还是使用stringbuilder,不是绝对的,要
18 //看情况。当拼接字符串很少的情况下,当然直接硬拼接字符串就行了。
19 
20 namespace stringbuilder和string比速度
21 {
22     class program
23     {
24         static void main(string[] args)
25         {
26             string str1 = string.empty;
27             stopwatch sw1 = new stopwatch();//计时运行的时间
28             sw1.start();
29             for (int i = 0; i < 10000; i++)
30             {
31                 str1 = str1 + i.tostring();
32             }
33             sw1.stop();
34             console.writeline("拼接字符串所耗费时间为:" + sw1.elapsedmilliseconds + "毫秒");
35             stringbuilder str2 = new stringbuilder(10000);
36             stopwatch sw2 = new stopwatch();
37             sw2.start();
38             for (int i = 0; i < 10000; i++)
39             {
40                 str2.append(i.tostring());
41             }
42             sw2.stop();
43             console.writeline("使用stringbuilder所耗费时间为:" + sw2.elapsedmilliseconds + "毫秒");
44             console.readkey();
45         }
46     }
47 }
48 
49 //运行结果:
50 //拼接字符串所耗费时间为:148毫秒
51 //使用stringbuilder所耗费时间为:1毫秒

 19.委托

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //个人理解概述:
 7 //委托是c#内重重重点,都知道启动程序时一定会启动主线程,主线程按着顺序向下执行。
 8 //在当点击一个控件需要执行一个以上的任务时,主线程就蒙了,还是会继续工作但是界面“假死”。
 9 //这是就要用到多线程,这个之后讲线程,c#是不允许跨线程的,这是委托就起到了作用。
10 //委托传值很方便,在之后就会发现委托和线程是个好基友。
11 //委托是有个好东西,他的好处我就不在这多说了,上网查查。
12 namespace delegate委托简单例子
13 {
14     class program
15     {
16         public delegate void name(string nm);//定义委托,定义委托时传参类型要与对应的方法参数类型一致
17         public static name nm;  //实例委托
18 
19         //给委托传递需要的方法
20         public static void name(string nm)
21         {
22             console.writeline("my name is {0}", nm);
23             console.readkey();
24         }
25 
26         static void main(string[] args)
27         {
28             nm = new name(name);
29             nm("毕小帅");//启动委托
30         }
31     }
32 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 泛型委托
 7 {
 8     class program
 9     {
10         public delegate void del<t>(t item);  
11         public static void notify(int i)
12         {
13             console.writeline("我是整数泛型委托");
14         }
15         public static void notify(string i)
16         {
17             console.writeline("我是字符串泛型委托");
18         } 
19 
20         static void show(string str)
21         {
22             console.writeline(str);
23         }
24         static string show(string str)
25         {
26             return str;
27         }
28 
29         static void main(string[] args)
30         { 
31             del<int> m1 = new del<int>(notify);
32             m1(1);
33             del<string> m2 = new del<string>(notify);
34             m2("");
35 
36             console.writeline();
37 
38             action<string> str = show;//action 是系统提供的不具有返回值
39             str("我是毕毕");
40 
41             console.writeline();
42             
43             func<string,string> str = show;//func泛型具有返回值,func内的第二个string是返回值类型
44             string ss = str("我是小毕");
45             console.writeline(ss);
46 
47             console.readkey();
48         }
49     }
50 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 匿名委托
 7 {
 8     class program
 9     {
10         static void main(string[] args)
11         {
12             list<string> names = new list<string>();
13             names.add("毕毕love丹丹");
14             names.add("毕毕");
15             names.add("丹丹");
16 
17             list<string> found = names.findall( //从前往后匹配相同字段
18                  delegate(string name)
19                  {
20                      return name.startswith("毕毕",
21                          stringcomparison.ordinalignorecase);
22                  });
23 
24             if (found != null)
25             {
26                 foreach (string str in found)
27                     console.writeline(str);
28             }
29             console.readkey();
30         }
31     }
32 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace lamda
 7 {
 8     public delegate void del1();
 9     public delegate void del2(string name);
10     public delegate string del3(string name);
11 
12     class program
13     {
14        static string n = "bb";
15 
16         static void main(string[] args)
17         {
18             del1 d1 = () => { console.writeline("无参"+" "+"b1"); }; 
19            
20             del2 d2 = (name) => { console.writeline("无参"+" "+name); };
21 
22             del3 d3 = (name) => { console.writeline("return 返回的是"+name); return name; };
23 
24             d1(); d2(n); d3(n);
25 
26             console.readkey();        
27         }
28     }
29 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 多播委托
 7 {
 8     public delegate void del();
 9     class program
10     {
11         static void main(string[] args)
12         {
13             del del = t1;
14 
15             del += t2;
16             del += t3;
17             del += t4;
18             del();
19 
20             console.readkey();
21         }
22 
23         public static void t1()
24         {
25             console.writeline("我是t1");
26         }
27         public static void t2()
28         {
29             console.writeline("我是t2");
30         }
31         public static void t3()
32         {
33             console.writeline("我是t3");
34         }
35         public static void t4()
36         {
37             console.writeline("我是t4");
38         }
39     }
40 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace class3
 7 {
 8     class program
 9     {
10        public delegate void del(string name); 
11         static void main(string[] args)
12         {
13             ////del del = new del(eat);
14             del del = eat1;//这俩种一样
15             del("毕小帅");
16 
17             test("毕小帅", eat1);
18             test("丹丹", eat2);
19 
20             //匿名委托
21             del d = delegate(string name)
22             {
23                 console.writeline("你好"+name);
24             };
25             d("毕毕");
26 
27             //lamda表达式 => 
28             del dd = (string name) => { console.writeline("hello" + name); };
29             dd("小毕");
30 
31             console.readkey();
32         }
33 
34         public static void test(string name, del del)
35         {
36             del(name);
37         }
38 
39         public static void eat1(string name)
40         {
41             console.writeline(name+"吃了吗");
42         }
43         public static void eat2(string name)
44         {
45             console.writeline(name + "吃了吗?");
46         }
47     }
48 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 委托事件
 7 {
 8     class program
 9     {
10         public delegate void salarycompute();        //声明一个代理类
11 
12         public class employee
13         {
14             public event salarycompute onsalarycompute;         //定义事件,将其与代理绑定
15 
16             public virtual void fireevent()       //触发事件的方法
17             {
18                 if (onsalarycompute != null)
19                 {
20                     onsalarycompute();      //触发事件
21                 }
22             }
23         }
24 
25         public class humanresource
26         {
27             public void salaryhandler()          //事件处理函数
28             {
29                 console.writeline("我可终于被打印出来了");     //只是打印一行字而已
30             }
31 
32             public static void main()
33             {
34                 employee ep = new employee();
35                 humanresource hr = new humanresource();
36                 ep.onsalarycompute += new salarycompute(hr.salaryhandler); //注册,委托连接到事件处理函数
37                 ep.fireevent();        //触发事件
38                 console.read();
39             }
40         }
41     }
42 }

收集一个类型不错的委托事件

  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 
  6 namespace 事件练习
  7 {
  8     class program
  9     {
 10 
 11         static void main()
 12         {
 13             god.start();
 14         }
 15         /// <summary> 
 16         /// 类eateventargs 必须继承自类eventargs,用来引发事件时封装数据 
 17         /// </summary> 
 18         public class eateventargs : eventargs
 19         {
 20             public string restrauntname; //饭店名称 
 21             public decimal moneyout; //准备消费金额 
 22         }
 23 
 24         /// <summary> 
 25         /// 这个委托用来说明处理吃饭事件的方法的方法头(模式) 
 26         /// </summary> 
 27         public delegate void eateventhandler(object sender, eateventargs e);
 28 
 29         /// <summary> 
 30         /// 引发吃饭事件(eateevent)的类master(主人),这个类必须 
 31         /// 1.声明一个名为eatevent的事件: public event eateventhandler eatevent; 
 32         /// 2.通过一个名为oneatevent的方法来引发吃饭事件,给那些处理此事件的方法传数据; 
 33         /// 3.说明在某种情形下引发事件呢?在饿的时候。用方法hungrg来模拟。 
 34         /// </summary> 
 35         public class master
 36         {
 37             //声明事件 
 38             public event eateventhandler eatevent;
 39 
 40             //引发事件的方法 
 41             public void oneatevent(eateventargs e)
 42             {
 43                 if (eatevent != null)
 44                 {
 45                     eatevent(this, e);
 46                 }
 47             }
 48 
 49             //当主人饿的时候,他会指定吃饭地点和消费金额。 
 50             public void hungry(string restrauntname, decimal moneyout)
 51             {
 52                 eateventargs e = new eateventargs();
 53                 e.restrauntname = restrauntname;
 54                 e.moneyout = moneyout;
 55 
 56                 console.writeline("主人说:");
 57                 console.writeline("我饿了,要去{0}吃饭,消费{1}元", e.restrauntname, e.moneyout);
 58 
 59                 //引发事件 
 60                 oneatevent(e);
 61             }
 62         }
 63 
 64         /// <summary> 
 65         /// 类servant(仆人)有一个方法arrangefood(安排食物)来处理主人的吃饭事件 
 66         /// </summary> 
 67         public class servant
 68         {
 69             public void arrangefood(object sender, eateventargs e)
 70             {
 71                 console.writeline();
 72                 console.writeline("仆人说:");
 73                 console.writeline("我的主人, 您的命令是 : ");
 74                 console.writeline("吃饭地点 -- {0}", e.restrauntname);
 75                 console.writeline("准备消费 -- {0}元 ", e.moneyout);
 76                 console.writeline("好的,正给您安排。。。。。。。。\n");
 77                 system.threading.thread.sleep(5000);
 78                 console.writeline("主人,您的食物在这儿,请慢用");
 79                 console.read();
 80             }
 81         }
 82 
 83         /// <summary> 
 84         /// 类god安排qinshihuang(秦始皇)的仆人是lisi(李斯),并让李斯的arrangefood 
 85         /// 方法来处理qinshihuang的吃饭事件:qinshihuang.eatevent += new eateventhandler(lishi.arrangefood); 
 86         /// </summary> 
 87         public class god
 88         {
 89             public static void start()
 90             {
 91                 master qinshihuang = new master();
 92                 servant lishi = new servant();
 93 
 94                 qinshihuang.eatevent += new eateventhandler(lishi.arrangefood);
 95 
 96                 //秦始皇饿了,想去希尔顿大酒店,消费5000元 
 97                 qinshihuang.hungry("希尔顿大酒店", 5000.0m);
 98             }
 99         }
100     }
101 }

 下面的是两个窗体简单传值(winform)

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 
10 namespace 窗体传值
11 {
12     public partial class form1 : form
13     {
14         public form1()
15         {
16             initializecomponent();
17         }
18         
19         private void button1_click(object sender, eventargs e)
20         {
21             form2 f2 = new form2(show);
22             f2.show();
23         }
24 
25         void show(string str)
26         {
27             label1.text = str;
28         }
29     }
30 }
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 
10 namespace 窗体传值
11 {
12     public delegate void del(string str);   //定义委托
13 
14     public partial class form2 : form
15     {
16         public del _del;
17         public form2(del del)//是将form1里的show()方法传过来了
18         {
19             this._del = del; //这个del可以想象成form1窗体里的show(....)方法
20             initializecomponent();
21         }
22         //时钟 也可以写成while 都是一个效果
23         private void timer1_tick(object sender, eventargs e)
24         {
25             _del(textbox1.text);//form2窗体开启时form1了的show()方法就成为了 委托调用的方法
26         }
27     }
28 }

 

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.diagnostics;
 6 
 7 namespace 调用exe
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             //process 是进程类
14             #region 这俩是一样的
15             process.start("notepad");//可以不加.exe =(notepad.exe)
16             //如果不是系统关联的程序指明路径就行了。
17             process.start(@"d:\program files (x86)\tencent\qq\bin\qq.exe");//这是我的qq安装路径
18             //我比较喜欢这个
19             process p = process.start("notepad.exe");
20             p.waitforexit();//等待外部程序退出后才能往下执行
21             #endregion
22 
23             #region 下面这俩是一样的
24             system.diagnostics.process exep = new system.diagnostics.process();
25             exep.startinfo.filename = "notepad";
26             exep.startinfo.arguments = @"c:\users\administrator\desktop\字符串的知识";
27             exep.startinfo.createnowindow = true;
28             exep.startinfo.useshellexecute = false;
29             exep.start();
30             exep.waitforexit();//关键,等待外部程序退出后才能往下执行
31             //我喜欢这个
32             processstartinfo startinfo = new processstartinfo("iexplore.exe");
33             startinfo.arguments = "www.baidu.com";//启动参数
34             startinfo.windowstyle = processwindowstyle.minimized;
35             process.start(startinfo);
36             #endregion
37         }
38     }
39 }

 20.编写dll文件、调用dll文件、传参、返回值

 

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 //一.创建dll文件
 6 //  1.在vs2010中创建class library 项目;(就是建个类)
 7 //    2.在类中写上下面代码
 8 //    3.3.按f6编译生成dll文件    不要按别的!!按f6!!!
 9 //二.调用dll文件(这步在新建的项目中)
10 namespace classlibrary1
11 {
12     public static class class1
13     {
14         public static string messages()
15         {
16             //定义了一个方法,此方法的作用就是返回下面字符串。
17             return "欢迎使用visual studio 2010 做的dll文件!";
18         }
19         static int s = 0;
20         public static int int(int ii)
21         {
22             for (int i = 0; i < 10; i++)
23             {
24                 s += ii;
25             }
26             return s;
27         }
28     }
29 }

 

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.runtime.interopservices;
10 using classlibrary1;
11 //二.调用dll文件
12 //将第一步生成的dll文件(\bin\debug\myfirstdll.dll)拷贝到新建的现在的项目文件夹下
13 //添加引用classlibrary1
14 //编辑代码(下面代码)
15 //编译运行
16 namespace 调用外部dll
17 {
18     public partial class form1 : form
19     {
20         public form1()
21         {
22             initializecomponent();
23         }
24 
25         [dllimport("user32.dll", entrypoint = "messageboxa")]
26 
27         static extern int msgbox(int hwnd, string msg, string caption, int type);
28         private void button1_click(object sender, eventargs e)
29         {
30             msgbox(0, " 这就是用 dllimport 调用 dll 弹出的提示框哦! ", " 小毕毕 ", 0x30);
31         }
32 
33         //调用自己写的dll文件
34         [dllimport("classlibrary1.dll")]
35 
36         static extern string messages();//
37         private void button2_click(object sender, eventargs e)
38         {
39             string str = class1.messages();
40             messagebox.show(str);
41         }
42 
43         [dllimport("classlibrary1.dll")]
44 
45         static extern int int();
46         private void button3_click(object sender, eventargs e)
47         {
48             int s = class1.int(10);
49             messagebox.show(s.tostring());        
50         }
51     }
52 }

21.c# 操作xml 

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 using system.xml;
 7 namespace _03创建xml
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             //通过代码来创建xml文档
14             //1、引用命名空间
15             //2、创建xml文档对象
16             xmldocument doc = new xmldocument();
17             //3、创建第一个行描述信息,并且添加到doc文档中
18             xmldeclaration dec = doc.createxmldeclaration("1.0", "utf-8", null);
19             doc.appendchild(dec);
20             //4、创建根节点
21             xmlelement books = doc.createelement("books");
22             //将根节点添加到文档中
23             doc.appendchild(books);
24 
25             //5、给根节点books创建子节点
26             xmlelement book1 = doc.createelement("book");
27             //将book添加到根节点
28             books.appendchild(book1);
29 
30 
31             //6、给book1添加子节点
32             xmlelement name1 = doc.createelement("name");
33             name1.innertext = "毕毕";
34             book1.appendchild(name1);
35 
36             xmlelement price1 = doc.createelement("price");
37             price1.innertext = "10";
38             book1.appendchild(price1);
39 
40             xmlelement des1 = doc.createelement("des");
41             des1.innertext = "好看";
42             book1.appendchild(des1);
43 
44             xmlelement book2 = doc.createelement("book");
45             books.appendchild(book2);
46 
47 
48             xmlelement name2 = doc.createelement("name");
49             name2.innertext = "毕毕";
50             book2.appendchild(name2);
51 
52             xmlelement price2= doc.createelement("price");
53             price2.innertext = "10";
54             book2.appendchild(price2);
55 
56             xmlelement des2 = doc.createelement("des");
57             des2.innertext = "好看";
58             book2.appendchild(des2);
59 
60             doc.save("books.xml");
61             console.writeline("保存成功");
62             console.readkey();
63         }
64     }
65 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 using system.xml;
 7 namespace _4_创建带属性的xml文档
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             xmldocument doc = new xmldocument();
14             xmldeclaration dec = doc.createxmldeclaration("1.0", "utf-8","yes");
15             doc.appendchild(dec);
16 
17             xmlelement order = doc.createelement("order");
18             doc.appendchild(order);
19 
20             xmlelement customername = doc.createelement("customername");
21             customername.innerxml = "<p>我是一个p标签</p>";
22             order.appendchild(customername);
23 
24             xmlelement customernumber = doc.createelement("customernumber");
25             customernumber.innertext = "<p>我是一个p标签</p>";
26             order.appendchild(customernumber);
27 
28 
29             xmlelement items = doc.createelement("items");
30             order.appendchild(items);
31 
32             xmlelement orderitem1 = doc.createelement("orderitem");
33             //给节点添加属性
34             orderitem1.setattribute("name", "充气**");//嘿嘿
35             orderitem1.setattribute("count", "10");
36             items.appendchild(orderitem1);
37 
38             xmlelement orderitem2 = doc.createelement("orderitem");
39             //给节点添加属性
40             orderitem2.setattribute("name", "充气**");
41             orderitem2.setattribute("count", "10");
42             items.appendchild(orderitem2);
43 
44             xmlelement orderitem3 = doc.createelement("orderitem");
45             //给节点添加属性
46             orderitem3.setattribute("name", "充气**");
47             orderitem3.setattribute("count", "10");
48             items.appendchild(orderitem3);
49 
50             doc.save("xml.xml");
51             console.writeline("保存成功");
52             console.readkey();
53 
54             
55         }
56     }
57 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 using system.xml;
 7 using system.io;
 8 namespace _5_追击xml
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             //追加xml文档
15             xmldocument doc = new xmldocument();
16             xmlelement books;
17             if (file.exists("books.xml"))
18             {
19                 //如果文件存在 加载xml
20                 doc.load("books.xml");
21                 //获得文件的根节点
22                 books = doc.documentelement;
23             }
24             else
25             {
26                 //如果文件不存在
27                 //创建第一行
28                 xmldeclaration dec = doc.createxmldeclaration("1.0", "utf-8", null);
29                 doc.appendchild(dec);
30                 //创建跟节点
31                 books = doc.createelement("books");
32                 doc.appendchild(books);
33             }
34             //5、给根节点books创建子节点
35             xmlelement book1 = doc.createelement("book");
36             //将book添加到根节点
37             books.appendchild(book1);
38 
39 
40             //6、给book1添加子节点
41             xmlelement name1 = doc.createelement("name");
42             name1.innertext = "c#开发大全";
43             book1.appendchild(name1);
44 
45             xmlelement price1 = doc.createelement("price");
46             price1.innertext = "110";
47             book1.appendchild(price1);
48 
49             xmlelement des1 = doc.createelement("des");
50             des1.innertext = "看不懂";
51             book1.appendchild(des1);
52 
53 
54             doc.save("books.xml");
55             console.writeline("保存成功");
56             console.readkey();
57 
58         }
59     }
60 }
  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 using system.threading.tasks;
  6 using system.xml;
  7 
  8 namespace _6_读取xml文档
  9 {
 10     class program
 11     {
 12         static void main(string[] args)
 13         {
 14             //比较综合点
 15             xmldocument doc = new xmldocument();
 16             doc.load("books.xml");
 17             xmlnode root = doc.documentelement;
 18             xmlnodelist nodelist = root.childnodes;
 19             foreach (xmlnode node in nodelist)
 20             {
 21                 console.writeline(node.name);
 22                 if (node.name == "book")
 23                 {
 24                     //找到name节点,进行操作
 25                     xmlnodelist xnl = doc.selectnodes("/books/book/name");
 26                     foreach (xmlnode nd in xnl)
 27                     {
 28                         console.writeline(nd.innertext);
 29                     }
 30                 }
 31             }
 32             console.readkey();
 33         }
 34     }
 35 }
 36 #region 在网上一位博客那里收集过来了,我看他的资料我才会xml操作。我全部复制下来了
 37 //c#操作xml时,要引入命名空间using system.xml
 38 
 39 //获取根节点的方法:
 40 //1、知道根节点名称:
 41 //xmlnode root = xmldoc.selectsinglenode("根节点名称");
 42 //2、不知道根节点名称:
 43 //xmlelement root = xmldoc.documentelement;
 44 //xml中node(节点)和element(元素)的区别(还是不太明白)
 45 //1、element是一个小范围的定义,必须含有完整信息的结点才能叫做元素。例如:<div>内容</div>,一个元素一定是一个节点,一个节点不一定是一个元素。
 46 //2、node是基本对象,attribute,element,text等都是node的子对象。
 47 //创建节点
 48 //1、createelement() 方法
 49 //有一个参数,两个参数,三个参数三种重载,参数类型均为string。
 50 //一个参数:createelement("元素名称")
 51 //两个参数:createelement("元素名称","元素的命名空间")
 52 //三个参数:createelement("元素的前缀","元素的名称","元素的命名空间")
 53 //2、createnode() 方法
 54 //三个参数 都为string类型
 55 //createnode("节点类型","节点名称","节点命名空间")
 56 //四个参数 都为string类型
 57 //createnode("节点类型","节点的前缀","节点名称","节点命名空间")
 58 //问题:节点前缀有什么作用?结点命名空间有什么作用?
 59 //增加节点:
 60 //1、appendchild() 方法
 61 //2、insertafter(要插入的节点,参考节点)  方法
 62 //3、insertbefore(要插入的节点,参考节点) 方法
 63 //增加节点属性:
 64 //setattribute("属性名","属性值")方法
 65 
 66 //删除节点属性:
 67 //removeattribute("属性名称")
 68 //给节点添加数据:
 69 //1、给节点的innertext赋值
 70 //例子:xmlelement ename = doc.createelement("name");
 71 //        ename.innertext = aaaaa;
 72 //2、添加xmltext节点,为其添加值
 73 //     添加节点元素
 74 //     将xmltext以子节点的方式添加给节点元素
 75 //例子: xmlelement ename = xmldoc.createelement("name");
 76 //        xmltext tname = xmldoc.createtextnode(aaaaa);
 77 //        ename.appendchild(tname);
 78 //寻找某个节点(寻找name节点):
 79 //先找到根节点,找出根节点下的节点列表(xmlnodelist),遍历每个节点。
 80 //再找每个节点下的节点列表,进行遍历,指导找到所需要的节点。
 81 //<msg>
 82 //<name></name>
 83 //<content></content>
 84 //</msg>
 85 //方法:
 86 //xmlnode root = xmldoc.selectsinglenode("msg");
 87 //xmlnodelist nodelist = root.childnodes;
 88 //foreach (xmlnode node in nodelist)
 89 //{
 90 //    if(node.name=="name")
 91 //    {
 92 //     找到name节点,进行操作
 93 //    }
 94 //}
 95 //删除节点
 96 //removeall(无参数)
 97 //removechild(要移除的节点)
 98 //更新节点
 99 //1、replacechild(新节点,老节点)
100 //建立一个新节点,替换老节点
101 //2、找到要更新的节点,重新设置其属性和数据
102 //用gridview显示xml文件中的数据
103 //view plaincopy to clipboardprint?
104 //dataset ds = new dataset();  
105 //ds.readxml(server.mappath("booksinfo.xml"));  
106 //gridview1.datasource = ds.tables[0];  
107 //gridview1.databind(); 
108 //dataset ds = new dataset();
109 //ds.readxml(server.mappath("booksinfo.xml"));
110 //gridview1.datasource = ds.tables[0];
111 //gridview1.databind();
112 //xml文件
113 //view plaincopy to clipboardprint?
114 //<?xml version="1.0" encoding="utf-8"?> 
115 //<bookstore> 
116 //  <book genre="ee" isbn="2-3631-4"> 
117 //    <title>三国演义</title> 
118 //    <author>lfdfd</author> 
119 //    <price>55.95</price> 
120 //  </book> 
121 //  <book isbn="2-3631-4"> 
122 //    <title>cs从入门到精通</title> 
123 //    <author>涨红</author> 
124 //    <price>58.3</price> 
125 //  </book> 
126 //  <book genre="计算机" isbn="2-3631-4"> 
127 //    <title>cs从入门到精通</title> 
128 //    <author>盖茨</author> 
129 //    <price>58.3</price> 
130 //  </book> 
131 //  <book genre="计算机" isbn="2-3631-4"> 
132 //    <title>cs从入门到精通</title> 
133 //    <author>盖茨</author> 
134 //    <price>58.3</price> 
135 //  </book> 
136 //</bookstore> 
137 //<?xml version="1.0" encoding="utf-8"?>
138 //<bookstore>
139 //  <book genre="ee" isbn="2-3631-4">
140 //    <title>三国演义</title>
141 //    <author>lfdfd</author>
142 //    <price>55.95</price>
143 //  </book>
144 //  <book isbn="2-3631-4">
145 //    <title>cs从入门到精通</title>
146 //    <author>涨红</author>
147 //    <price>58.3</price>
148 //  </book>
149 //  <book genre="计算机" isbn="2-3631-4">
150 //    <title>cs从入门到精通</title>
151 //    <author>盖茨</author>
152 //    <price>58.3</price>
153 //  </book>
154 //  <book genre="计算机" isbn="2-3631-4">
155 //    <title>cs从入门到精通</title>
156 //    <author>盖茨</author>
157 //    <price>58.3</price>
158 //  </book>
159 //</bookstore>
160 //显示效果:
161 
162 //删除属性为计算机的节点
163 //view plaincopy to clipboardprint?
164 //xmldocument xmldoc = new xmldocument();  
165 //xmldoc.load(server.mappath("xml/booksinfo.xml"));  
166 //xmlnodelist xnl = xmldoc.selectsinglenode("bookstore").childnodes;  
167 //foreach (xmlnode xn in xnl)  
168 //   {  
169 //      xmlelement xe = (xmlelement)xn;  
170 
171 //      if (xe.getattribute("genre") == "计算机")  
172 //         {  
173 //            xe.removeall();//删除属性=计算机的该节点的全部内容  
174 //              //xe.parentnode.removechild(xe);  
175 //          }  
176 
177 
178 //   }  
179 //xmldoc.save(server.mappath("xml/booksinfo.xml")); 
180 //xmldocument xmldoc = new xmldocument();
181 //xmldoc.load(server.mappath("xml/booksinfo.xml"));
182 //xmlnodelist xnl = xmldoc.selectsinglenode("bookstore").childnodes;
183 //foreach (xmlnode xn in xnl)
184 //   {
185 //      xmlelement xe = (xmlelement)xn;
186 //      if (xe.getattribute("genre") == "计算机")
187 //         {
188 //            xe.removeall();//删除属性=计算机的该节点的全部内容
189 //              //xe.parentnode.removechild(xe);
190 //          }
191 
192 //   }
193 //xmldoc.save(server.mappath("xml/booksinfo.xml"));
194 //xe.parentnode.removechild(xe)
195 //寻找到xe节点的父节点,再删除他的子节点。那么此节点(包括节点标记)将不存在。显示中将没有空行
196 //xe.removeall()
197 //移除节点内容,但是节点标签还在。显示中有空行
198 
199 #endregion
200 
201 #region
202 //读取xml节点内的数据内容
203 //xmldocument doc = new xmldocument();
204 ////加载要读取的xml
205 //doc.load("order.xml");
206 ////获得根节点
207 //xmlelement books = doc.documentelement;
208 ////获得子节点 返回节点的集合
209 //xmlnodelist xnl = books.childnodes;
210 //foreach (xmlnode item in xnl)
211 //{
212 //    console.writeline(item.innertext);
213 //}
214 //console.readkey();
215 
216 
217 ////读取带属性的xml文档           
218 //xmldocument doc = new xmldocument();
219 //doc.load("order.xml");
220 //xmlnodelist xnl = doc.selectnodes("/order/items/orderitem");
221 
222 //foreach (xmlnode node in xnl)
223 //{
224 //    console.writeline(node.attributes["name"].value);
225 //    console.writeline(node.attributes["count"].value);
226 //}
227 //console.readkey();
228 
229 
230 //改变属性的值
231 //xmldocument doc = new xmldocument();
232 //doc.load("order.xml");
233 //xmlnode xn = doc.selectsinglenode("/order/items/orderitem[@name='190']");
234 //xn.attributes["count"].value = "200";
235 //xn.attributes["name"].value = "颜世伟";
236 //doc.save("order.xml");
237 //console.writeline("保存成功");
238 
239 
240 //删除相应的的范围
241 //xmldocument doc = new xmldocument();
242 //doc.load("order.xml");
243 //xmlnode xn = doc.selectsinglenode("/order/items");
244 //xn.removeall();
245 //doc.save("order.xml");
246 //console.writeline("删除成功");
247 //console.readkey();
248 
249 
250 ////获得文档的根节点           
251 //xmldocument doc = new xmldocument();
252 //doc.load("books.xml");
253 //xmlnode root = doc.documentelement;
254 //xmlnodelist nodelist = root.childnodes;
255 //foreach (xmlnode node in nodelist)
256 //{
257 //    console.writeline(node.name);
258 //    //if(node.name=="name")
259 //    //{
260 //    // //找到name节点,进行操作
261 //    //}
262 //}
263 
264 
265 ////比较综合点
266 //xmldocument doc = new xmldocument();
267 //doc.load("order.xml");
268 //xmlnode root = doc.documentelement;
269 //xmlnodelist nodelist = root.childnodes;
270 //foreach (xmlnode node in nodelist)
271 //{
272 //    console.writeline(node.name);
273 //    if (node.name == "items")
274 //    {
275 //        //找到name节点,进行操作
276 //        xmlnodelist xnl = doc.selectnodes("/order/items/orderitem");
277 //        foreach (xmlnode nd in xnl)
278 //        {
279 //            console.writeline(nd.attributes["name"].value);
280 //            console.writeline(nd.attributes["count"].value);
281 //        }
282 //    }
283 //}
284 #endregion

所需要的xml文件,放在运行程序的当前目录下

 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3 -<books>
 4 
 5 
 6 -<book>
 7 
 8 <name>c#开发大全</name>
 9 
10 <price>110</price>
11 
12 <des>看不懂</des>
13 
14 </book>
15 
16 
17 -<book>
18 
19 <name>c#开发大全</name>
20 
21 <price>110</price>
22 
23 <des>看不懂</des>
24 
25 </book>
26 
27 
28 -<book>
29 
30 <name>c#开发大全</name>
31 
32 <price>110</price>
33 
34 <des>看不懂</des>
35 
36 </book>
37 
38 
39 -<book>
40 
41 <name>c#开发大全</name>
42 
43 <price>110</price>
44 
45 <des>看不懂</des>
46 
47 </book>
48 
49 </books>
 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3 -<books>
 4 
 5 
 6 -<book>
 7 
 8 <name>c#开发大全</name>
 9 
10 <price>110</price>
11 
12 <des>看不懂</des>
13 
14 </book>
15 
16 
17 -<book>
18 
19 <name>c#开发大全</name>
20 
21 <price>110</price>
22 
23 <des>看不懂</des>
24 
25 </book>
26 
27 </books>

 22.字符串大小写转换

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace class2
 7 {
 8     class program
 9     {
10         static void main(string[] args)
11         {
12             string[] names = { "abdc", "byl" };
13             prot(names);
14             prot(names);
15         }
16 
17         public static void prot(string[] name)
18         {
19             for (int i = 0; i < name.length; i++)
20             {
21                 name[i] = name[i].toupper();//转大写
22                 console.writeline(name[i]);
23             }
24             // console.readkey();
25         }
26 
27         public static void prot(string[] name)
28         {
29             for (int i = 0; i < name.length; i++)
30             {
31                 name[i] = name[i].tolower();
32                 console.writeline(name[i]);
33             }
34             console.readkey();
35         }
36     }
37 }

23.单例模式
简单的:

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 
10 namespace csharp_特色_单体模式
11 {
12     public partial class form1 : form
13     {
14         public form1()
15         {
16             initializecomponent();
17         }
18 
19         private void button1_click(object sender, eventargs e)
20         {
21             form2 f2 = form2.instance;
22             
23             f2.show();
24         }
25     }
26 }
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 
10 namespace csharp_特色_单体模式
11 {
12     public partial class form2 : form
13     {
14         private form2()
15         {
16             initializecomponent();
17         }
18         //不要说c#太懒了,这叫智慧,嘿嘿
19         public static readonly form2 instance = new form2();
20     }
21 
22     //核心在这里
23         //public class singleton
24         //{
25         //    private singleton(){}
26         //    public static readonly singleton instance = new singleton();
27         //}  
28 }

相比之下复杂一点点的:

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.threading.tasks;
 9 using system.windows.forms;
10 
11 namespace _2_单例模式
12 {
13     public partial class form1 : form
14     {
15         public form1()
16         {
17             initializecomponent();
18         }
19 
20         private void form1_load(object sender, eventargs e)
21         {
22             this.ismdicontainer = true;//指定当前窗体为父窗体
23             this.windowstate = formwindowstate.maximized;    //窗体加载时,窗体为最大化  
24         }
25 
26         private void button1_click(object sender, eventargs e)
27         {
28             form2 frm2 = form2.getsingle();
29             frm2.mdiparent = this;//指定父窗体
30 
31             frm2.show();
32         }
33     }
34 }
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.threading.tasks;
 9 using system.windows.forms;
10 
11 namespace _2_单例模式
12 {
13     public partial class form2 : form
14     {
15         //全局唯一的单例
16         public static form2 frmsingle=null;
17 
18         public form2()
19         {
20             initializecomponent();
21         }
22 
23         public static form2 getsingle()
24         {
25             if (frmsingle == null)
26             {
27                 frmsingle = new form2();
28             }
29             return frmsingle;
30         }   
31     }
32     //核心就是 这个
33     //public class singleton
34     //    {
35     //        private static singleton _instance = null;
36     //        private singleton() { }
37     //        public static singleton createinstance()
38     //        {
39     //            if (_instance == null)
40     //            {
41     //                _instance = new singleton();                    
42     //            }
43     //            return _instance;
44     //        }
45     //    }
46 }

 线程安全的单例模式

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 
10 namespace _2.线程安全的单例模式singleton
11 {
12     public partial class form1 : form
13     {
14         public form1()
15         {
16             initializecomponent();
17         }
18 
19         private void button1_click(object sender, eventargs e)
20         {
21             form2 f2 = form2.ci();
22             f2.show();
23         }
24     }
25 }
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 
10 namespace _2.线程安全的单例模式singleton
11 {
12     public partial class form2 : form
13     {
14         private volatile static form2 ins = null;
15         private static readonly object lockhelper = new object();
16         private form2()
17         {
18             initializecomponent();
19         }
20 
21         public static form2 ci()
22         {
23             if (ins == null)
24             {
25                 lock (lockhelper)
26                 {
27                     if (ins == null)
28                         ins = new form2();
29                 }
30             }
31             return ins;
32         }
33     }
34     //第二种考虑了线程安全,不过有点烦,但绝对是正规写法,经典的一叉 
35     //核心就是这个
36     //public class singleton
37     //{
38     //    private volatile static singleton _instance = null;
39     //    private static readonly object lockhelper = new object();
40     //    private singleton() { }
41     //    public static singleton createinstance()
42     //    {
43     //        if (_instance == null)
44     //        {
45     //            lock (lockhelper)
46     //            {
47     //                if (_instance == null)
48     //                    _instance = new singleton();
49     //            }
50     //        }
51     //        return _instance;
52     //    }
53     //}
54 }

 24.文件、文件夹操作(path、file、directory)

 

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.io;
 10 
 11 namespace 文件操作
 12 {
 13     public partial class form1 : form
 14     {
 15         public form1()
 16         {
 17             initializecomponent();
 18         }
 19 
 20         private void form1_load(object sender, eventargs e)
 21         {
 22             //这是控制台程序,我就写在这里方便理解
 23             ////注意:这样是没有在桌面创建任何文件的
 24             //string path = @"c:\users\administrator\desktop\new.txt";//我的桌面 目录
 25             //console.writeline(path.getdirectoryname(path));//得到 文件目录
 26             //console.writeline(path.changeextension(path, "jpg"));//等到文件目录,改变文件格式
 27             //console.readkey();
 28         }
 29 
 30         private void btncreate_click(object sender, eventargs e)
 31         {
 32             //using system.io;
 33             file.create(@"c:\users\administrator\desktop\new.txt");
 34             messagebox.show("创建成功");
 35         }
 36 
 37         private void btncopy_click(object sender, eventargs e)
 38         {
 39             file.copy(@"c:\users\administrator\desktop\new.txt", @"c:\users\administrator\desktop\abc.txt", true);//加上true可以覆盖源文件,不加 不可覆盖
 40             messagebox.show("拷贝成功");
 41         }
 42 
 43         private void btnmove_click(object sender, eventargs e)
 44         {
 45             //也可以用这种方式重命名
 46             file.move(@"c:\users\administrator\desktop\new.txt", @"c:\users\administrator\desktop\new_old.txt");
 47             messagebox.show("移动成功");
 48         }
 49 
 50         private void btndelete_click(object sender, eventargs e)
 51         {
 52             file.delete(@"c:\users\administrator\desktop\new_old.txt");
 53             messagebox.show("删除成功");
 54         }
 55 
 56         //下面的是读取和写入操作,首先要确定有目标文件就是需要使用的文件(在指定目录建个txt文件)
 57         //我使用的是c:\users\administrator\desktop\毕毕love丹丹.txt
 58         //定义个全局变量 方便使用
 59         public static string strtxt = @"c:\users\administrator\desktop\毕毕love丹丹.txt";
 60 
 61         private void btnwriter_click(object sender, eventargs e)
 62         {
 63             //file类写入
 64             //其实写入任何东西都是没用处的,都被下面的write...给覆盖了
 65             //想要看见自己输入的内容把writealllines和writealltext两行注释掉就行了
 66             string str = txtwr.text;
 67             byte[] buffer = encoding.default.getbytes(str);
 68             file.writeallbytes(strtxt, buffer);
 69             
 70             file.writealllines(strtxt, new string[] { "张三", "李四", "王五", "赵六" });
 71            
 72             file.writealltext(strtxt, "大家请叫我‘毕小帅’");//覆盖
 73 
 74             file.appendalltext(strtxt, "没有覆盖哟");
 75            
 76             messagebox.show("成功");
 77         }
 78 
 79         private void btnreader_click(object sender, eventargs e)
 80         {
 81             txtwr.text = "";
 82             //使用file类来读取数据
 83             byte[] buffer = file.readallbytes(strtxt);
 84             string str = encoding.utf8.getstring(buffer, 0, buffer.length);
 85             txtwr.text = str + '\n';
 86 
 87             //编码:把字符串以怎样形式存储为二进制  ascii  gbk  gb2312   utf-8  
 88            
 89             string[] str1 = file.readalllines(strtxt, encoding.default);
 90             for (int i = 0; i < str1.length; i++)
 91             {
 92                 txtwr.appendtext(str1[i]);
 93             }
 94 
 95             ////readalllines和readalltext都是读取文件的所有行
 96             ////不同的是 第一个读取所有行的集合,第二个是读取文件内的整个的 全部的数据
 97             //string str2 = file.readalltext(strtxt, encoding.default);
 98             //txtwr.appendtext(str2);
 99         }
100     }
101 }

25.超市管理系统(控制台应用程序)

先看一下输出结果:

 

 需要的文件:

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 //我仿照一个培训老师写的教程、
 7 namespace 超市管理系统
 8 {
 9     class prm_main
10     {
11         static void main(string[] args)
12         {
13             //为了方便理解,我把类名和方法名都写成了汉字,工作中不可以这样,建议写成简写英文
14 
15             //无论做什么,首先把流程搞清楚
16             //   看要求:
17             //   四种商品--酱油、香蕉、手机、电脑
18             //   每种商品都在单独的货架上
19             //   每种商品都是有id、价格、名字
20             //   用户购买商品的优惠,如何打折。得出总价钱
21             //知道这些就够了,简单的管理系统就有思路了。(我感觉我比那位培训老师都讲的仔细,嘿嘿)
22 
23             //我的思路:
24             //1、用户要买东西首先需要有商品
25             //2、每个商品要有id、价格、名字
26             //3、商品不可能在超市里是乱放的,要有分类
27             //4、然后就是用户购买了,按照买的个数*价格*打折
28 
29             //思路很清晰了,开始写了
30             //1.建个商品的父类 封装商品的(id、价格、名字)---商品father.cs
31             //2.写出四种商品的类
32             //3.商品确定了,把商品放在规定的货架上--超市.cs
33             //4.商品全部搞定后,接下来就是客户购买了,先写个打折的父类(因为好几种打折的方式,来重写父类)
34             //5.实现打折的方式---打折_满减.cs
35             //6.实现打折的方式---打折_折扣率.cs
36             //7.还需要个不打折的付款---不打折.cs
37             //8.准备工作全部结束了,最后一步就是用户购物了
38             //好了全部搞定
39             /*******************************************************/
40 
41             //接下来就是用户购物了
42 
43             用户购物 sm = new 用户购物();
44             //展示货物
45             sm.展示货物();
46             //跟用户交互
47             sm.用户交互();
48             console.readkey();
49         }
50     }
51 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     class 商品father
 9     {
10         public double price
11         {
12             get;
13             set;
14         }
15 
16         public string name
17         {
18             get;
19             set;
20         }
21 
22         public string id
23         {
24             get;
25             set;
26         }
27 
28         public 商品father(string id, double price, string name)
29         {
30             this.id = id;
31             this.price = price;
32             this.name = name;
33         }
34     }
35 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     class 电脑 : 商品father
 9     {
10         public 电脑(string id, double price, string name)
11             : base(id, price, name)
12         {
13 
14         }
15     }
16 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     class 手机 : 商品father
 9     {
10         public 手机(string id, double price, string name)
11             : base(id, price, name)
12         {
13 
14         }
15     }
16 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     class 香蕉 : 商品father
 9     {
10         public 香蕉(string id, double price, string name)
11             : base(id, price, name)
12         {
13 
14         }
15     }
16 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     class 酱油 : 商品father
 9     {
10         public 酱油(string id, double price, string name)
11             : base(id, price, name)
12         {
13 
14         }
15     }
16 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     class 超市
 9     {
10         list<list<商品father>> list = new list<list<商品father>>();
11 
12         /// <summary>
13         ///向用户展示货物
14         /// </summary>
15         public void 展示货物()
16         {
17             foreach (var item in list)
18             {
19                 console.writeline("我们超市有:" + item[0].name + "," + "\t" + "有" + item.count + "个," + "\t" + "每个" + item[0].price + "元");
20             }
21         }
22         //list[0]存储acer电脑
23         //list[1]存储三星手机
24         //list[2]存储酱油
25         //list[3]存储香蕉
26         /// <summary>
27         /// 在创建仓库对象的时候 像仓库中添加货架
28         /// </summary>
29         public 超市()
30         {
31             list.add(new list<商品father>());
32             list.add(new list<商品father>());
33             list.add(new list<商品father>());
34             list.add(new list<商品father>());
35         }
36         /// <summary>
37         /// 进货
38         /// </summary>
39         /// <param name="strtype">货物的类型</param>
40         /// <param name="count">货物的数量</param>
41         public void jinpros(string strtype, int count)
42         {
43             for (int i = 0; i < count; i++)
44             {
45                 switch (strtype)
46                 {
47                     case "手机": list[0].add(new 香蕉(guid.newguid().tostring(), 1000, "手机"));
48                         break;
49                     case "电脑": list[1].add(new 手机(guid.newguid().tostring(), 2000, "电脑"));
50                         break;
51                     case "酱油": list[2].add(new 酱油(guid.newguid().tostring(), 10, "酱油"));
52                         break;
53                     case "香蕉": list[3].add(new 电脑(guid.newguid().tostring(), 50, "香蕉"));
54                         break;
55                 }
56             }
57         }
58         /// <summary>
59         /// 从仓库中提取货物
60         /// </summary>
61         /// <param name="strtype"></param>
62         /// <param name="count"></param>
63         /// <returns></returns>
64         public 商品father[] qupros(string strtype, int count)
65         {
66             商品father[] pros = new 商品father[count];
67             for (int i = 0; i < pros.length; i++)
68             {
69                 switch (strtype)
70                 {
71                     case "手机":
72                         pros[i] = list[0][0];
73                         list[0].removeat(0);
74                         break;
75                     case "电脑": pros[i] = list[1][0];
76                         list[1].removeat(0);
77                         break;
78                     case "酱油": pros[i] = list[2][0];
79                         list[2].removeat(0);
80                         break;
81                     case "香蕉": pros[i] = list[3][0];
82                         list[3].removeat(0);
83                         break;
84                 }
85             }
86             return pros;
87         }
88     }
89 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     /// <summary>
 9     /// 打折的父类 抽象类---需要重写父类
10     /// </summary>
11     abstract class 打折father
12     {
13         /// <summary>
14         /// 计算打折后应付多少钱
15         /// </summary>
16         /// <param name="realmoney">打折前应付的价钱</param>
17         /// <returns>打折后应付的钱</returns>
18         public abstract double 付钱(double realmoney);
19     }
20 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     /// <summary>
 9     /// 买m元 送n元
10     /// </summary>
11     class 打折_满减 : 打折father
12     {
13         //买500送100
14         public double m
15         {
16             get;
17             set;
18         }
19 
20         public double n
21         {
22             get;
23             set;
24         }
25 
26         public 打折_满减(double m, double n)
27         {
28             this.m = m;
29             this.n = n;
30         }
31         public override double 付钱(double realmoney)
32         {
33             //600 -100
34             //1000-200
35             //1200 
36             if (realmoney >= this.m)
37             {
38                 return realmoney - (int)(realmoney / this.m) * this.n;
39             }
40             else
41             {
42                 return realmoney;
43             }
44         }
45     }
46 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     /// <summary>
 9     /// 按折扣率打折
10     /// </summary>
11     class 打折_折扣率 : 打折father
12     {
13         /// <summary>
14         /// 折扣率
15         /// </summary>
16         public double rate
17         {
18             get;
19             set;
20         }
21 
22         public 打折_折扣率(double rate)
23         {
24             this.rate = rate;
25         }
26         public override double 付钱(double realmoney)
27         {
28             return realmoney * this.rate;
29         }
30 
31     }
32 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     /// <summary>
 9     /// 不打折 该多少钱就多少钱
10     /// </summary>
11     class 不打折 : 打折father
12     {
13         public override double 付钱(double realmoney)
14         {
15             return realmoney;
16         }
17     }
18 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 超市管理系统
 7 {
 8     class 用户购物
 9     {
10         //创建仓库对象
11         超市 ck = new 超市();
12         /// <summary>
13         /// 创建超市对象的时候,给仓库的货架上导入货物
14         /// </summary>
15         public 用户购物()
16         {
17             ck.jinpros("酱油", 1000);
18             ck.jinpros("香蕉", 1000);
19             ck.jinpros("手机", 1000);
20             ck.jinpros("电脑", 1000);
21         }
22 
23         /// <summary>
24         /// 跟用户交互的过程
25         /// </summary>
26         public void 用户交互()
27         {
28             console.writeline("欢迎观临,请问您需要些什么?");
29             console.writeline("我们有 酱油、香蕉、手机、电脑");
30             string strtype = console.readline();
31             console.writeline("您需要多少?");
32             int count = convert.toint32(console.readline());
33             //去仓库取货物
34             商品father[] pros = ck.qupros(strtype, count);
35             //下面该计算价钱了
36             double realmoney = 总价钱(pros);
37             console.writeline("您总共应付{0}元", realmoney);
38             console.writeline("请选择您的打折方式 1--不打折 2--打九折  3--打85 折  4--买300送50  5--买500送100");
39             string input = console.readline();
40             //通过简单工厂的设计模式根据用户的舒服获得一个打折对象
41             打折father cal = 打折_工厂(input);
42             double totalmoney = cal.付钱(realmoney);
43             console.writeline("打完折后,您应付{0}元", totalmoney);
44             console.writeline("以下是您的购物信息");
45             foreach (var item in pros)
46             {
47                 console.writeline("货物名称:" + item.name + "," + "\t" + "货物单价:" + item.price + "," + "\t" + "货物编号:" + item.id);
48             }
49         }
50 
51         /// <summary>
52         /// 根据用户的选择打折方式返回一个打折对象
53         /// </summary>
54         /// <param name="input">用户的选择</param>
55         /// <returns>返回的父类对象 但是里面装的是子类对象</returns>
56         public 打折father 打折_工厂(string input)
57         {
58             打折father cal = null;
59             switch (input)
60             {
61                 case "1": cal = new 不打折();
62                     break;
63                 case "2": cal = new 打折_折扣率(0.9);
64                     break;
65                 case "3": cal = new 打折_折扣率(0.85);
66                     break;
67                 case "4": cal = new 打折_满减(300, 50);
68                     break;
69                 case "5": cal = new 打折_满减(500, 100);
70                     break;
71             }
72             return cal;
73         }
74 
75         /// <summary>
76         /// 根据用户买的货物计算总价钱
77         /// </summary>
78         /// <param name="pros"></param>
79         /// <returns></returns>
80         public double 总价钱(商品father[] pros)
81         {
82             double money = 0;
83             //realmoney = pros[0].price * pros.length;
84 
85             for (int i = 0; i < pros.length; i++)
86             {
87                 money += pros[i].price;
88 
89                 // realmoney = pros[i] * pros.length;
90             }
91             return money;
92         }
93 
94         public void 展示货物()
95         {
96             ck.展示货物();
97         }
98     }
99 }

 26.小游戏(石头剪刀布)

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 
 10 namespace 石头剪刀布
 11 {
 12     public partial class form1 : form
 13     {
 14         public form1()
 15         {
 16             initializecomponent();
 17             // button1.click += (s, e) => { shitou(); };
 18             button2.click += (s, e) => { jiandao(); };//别忘了,事件只能出现在+=、-=左边
 19             button3.click += (d, e) => { bu(); };
 20         }
 21         //其实button1.click += (s, e) => { shitou(); };和下面的这写法是一样的
 22         private void button1_click(object sender, eventargs e)
 23         {
 24             shitou();
 25         }
 26         //石头
 27         public void shitou()
 28         {
 29             label4.text = button1.text;
 30             label3.text = bj(toint(), pc());
 31         }
 32         //剪刀
 33         public void jiandao()
 34         {
 35             label4.text = button2.text;
 36             label3.text = bj(toint(), pc());
 37         }
 38 
 39         //布
 40         public void bu()
 41         {
 42             label4.text = button3.text;
 43             label3.text = bj(toint(), pc());
 44         }
 45 
 46         /// <summary>
 47         /// 电脑随机显示,还有相应的值替代它
 48         /// </summary>
 49         /// <returns></returns>
 50         public int pc()
 51         {
 52             random ran = new random();
 53             int vpc = ran.next(1, 4);
 54             // string strpc;//这样写会浪费资源,在堆中要开辟很多空间
 55             //这样,每次调用pc方法时strpc都是初始为空的。
 56             //重要的是string类型是引用类型。
 57             string strpc = string.empty;//初始为空
 58             switch (vpc)
 59             {
 60                 case 1:
 61                     strpc = "石头";
 62                     break;
 63                 case 2:
 64                     strpc = "剪刀";
 65                     break;
 66                 case 3:
 67                     strpc = "布";
 68                     break;
 69                 default:
 70                     throw new exception("未知错误");
 71             }
 72             label5.text = strpc;
 73             return vpc;
 74         }
 75         /// <summary>        
 76         /// 把剪刀石头布用数字表示
 77         /// </summary>
 78         /// <returns></returns>
 79         public int toint()
 80         {
 81             int n;
 82             switch (label4.text)
 83             {
 84                 case "石头":
 85                     n = 1;
 86                     break;
 87                 case "剪刀":
 88                     n = 2;
 89                     break;
 90                 case "布":
 91                     n = 3;
 92                     break;
 93                 default:
 94                     throw new exception("出错了");
 95             }
 96             return n;
 97         }
 98         //比较
 99         public string bj(int user, int pc)
100         {
101             int tmp = user - pc;
102             string bj = string.empty;
103             if (tmp == 1 || tmp == -2)
104             {
105                 bj = "你输了";
106             }
107             else if (tmp == 0)
108             {
109                 bj = "平局";
110             }
111             else
112             {
113                 bj = "你赢了";
114             }
115             return bj;
116         }
117     }
118 }

27.英汉词典
    

 

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.io;
 10 
 11 namespace 英汉词典
 12 {
 13     public partial class form1 : form
 14     {
 15         public form1()
 16         {
 17             initializecomponent();
 18         }
 19         //第一步,我是先把英汉词典.txt数据源的内容储存起来,方便使用
 20         //首先用一个泛型字典存储英汉词典.txt里的内容
 21         //反省字典是(dictionary<,>)这样的,里面是键值对
 22         //每行数据必须要有一个唯一的键不可以重复,尾随的数据可以重复
 23 
 24         //new 一个泛型字典
 25         dictionary<string, string> dic = new dictionary<string, string>();
 26         //new 一个泛型list
 27         list<string> list = new list<string>();
 28 
 29         //读取英汉词典.txt文件,这就要知道它的路径了
 30         //我个人建议是把英汉词典.txt文件放在相对路径下,因为打包之后方便使用
 31 
 32         //绝对路径下读取文件
 33         //加上@,便于后面的符号转换
 34         //encoding.default是选择当前系统默认的字体编码
 35         //string[] strarr = file.readalllines(@"c:\users\administrator\desktop\英汉词典.txt",encoding.default);
 36         //相对路径下读取文件
 37         //我选择的是相对路径
 38         string[] strarr = file.readalllines(@"英汉词典.txt", encoding.default);
 39 
 40         //窗体加载时自动运行
 41         private void form1_load(object sender, eventargs e)
 42         {
 43             stime();
 44             label2.text = "您查询的结果:";
 45             label1.text = "";
 46 
 47             //遍历每一个行,每行都是两个元素,英文和中文
 48             for (int i = 0; i < strarr.length; i++)
 49             {
 50                 //使用split方法移除单个空字符
 51                 string[] strarr1 = strarr[i].split(new char[] { ' ' }, stringsplitoptions.removeemptyentries);
 52                 //避免重复添加
 53                 //contains是包含的意思
 54                 if (!dic.keys.contains(strarr1[0]))
 55                 {
 56                     //其实这样也就可以了,但是作为一个严谨的程序员,我还是给这一段加个判断
 57                     //将数组里的英文和中文填到泛型字典里
 58                     dic.add(strarr1[0], strarr1[1]);
 59                     //将英文添加到泛型list里
 60                     //这样list内的数据都是dic内的键值
 61                     list.add(strarr1[0]);
 62                 }
 63             }
 64             //为了让程序运行起来想过能高大上一些,就填了这一下的代码
 65             autocompletestringcollection strings = new autocompletestringcollection();
 66             // 所有list泛型的英文单词转换成数组 添加到 strings里
 67             strings.addrange(list.toarray());
 68             textbox1.autocompletecustomsource = strings;  //然后赋给文本框的 自动补全 所需的资源 属性
 69             textbox1.autocompletesource = autocompletesource.customsource;  //指定 customsource 为数据源
 70             textbox1.autocompletemode = autocompletemode.suggest; //启动自动补全模式
 71         }
 72         //以上读取英汉字典.txt的操作,已经搞定
 73         //接下来就开始实现了
 74 
 75 
 76         private void textbox1_textchanged(object sender, eventargs e)
 77         {
 78             //文本框内若是没有数据,就不显示label1
 79             if (textbox1.text == "")
 80             {
 81                 label1.text = "";
 82             }
 83 
 84             //开始查找,文本框内与泛型字典键相同就把数据显示出来
 85             //trim()是把空白的字符去掉
 86             if (dic.keys.contains(textbox1.text.trim()))
 87             {
 88                 //用键值找到数据,显示在textbox2中
 89                 textbox2.text = dic[textbox1.text.trim()];
 90 
 91                 //因为搜索到了结果,所以在线搜索不显示
 92                 linklabel1.visible = false;
 93                 label1.text = "";
 94                 label2.text = "您查询的结果:";
 95                 timer.stop();
 96                 ltime = 0;
 97             }
 98             else if (textbox1.text == "")
 99             {
100                 textbox2.text = "请输入要查询单词";
101                 linklabel1.visible = false;
102                 timer.stop();
103                 ltime = 0;
104             }
105             else
106             {
107                 textbox2.text = "正在搜索";
108                 //计时开始
109                 timer.start();
110                 label2.text = "您查询的结果:";
111 
112             }
113 
114         }
115         //以上显示部分也基本搞定
116         //对了,把在线查询实现出来
117         private void linklabel1_linkclicked(object sender, linklabellinkclickedeventargs e)
118         {
119             //因为我这有360浏览器,经常被终结,我就添加了try catch
120             try
121             {
122                 system.diagnostics.process.start("explorer.exe", "http://www.youdao.com/w/" + textbox1.text.trim());
123             }
124             catch
125             {
126                 messagebox.show("通过其他方式已将查询关闭");
127             }
128         }
129 
130         private void label2_click(object sender, eventargs e)
131         {
132 
133         }
134 
135         //为了让程序能高大上,我设置在20秒内若是没有查到结果就显示在线查找
136         //也可以按键盘回车键直接进行查询结果
137 
138         //定义个查找所用时间
139         public int ltime = 0;
140         //定义个计时器
141         public timer timer;
142 
143         public void stime()
144         {
145             timer = new timer();
146             //一秒间隔
147             timer.interval = 1000;
148             timer.tick += (s, e) =>
149                 {
150                     ltime++;
151                     label1.text = ltime.tostring();//显示查询几秒
152 
153                     if (ltime >= 20)
154                     {
155                         label1.text = "收索时间大于20秒已超时";
156                         label2.text = "对不起,系统不包含您输入的单词";
157                         textbox2.text = "";
158                         //显示网站链接
159                         linklabel1.visible = true;
160                         linklabel1.text = "对不起请尝试使用(有道youdao)在线翻译:" + "\r\n\n\t" + textbox1.text.trim();
161                         timer.stop();
162                         ltime = 0;
163 
164                         //使linkwebsearch控件显示的网址在textbox控件上面
165                         linklabel1.bringtofront();
166                     }
167                     else//那就是20秒内显示出结果了
168                     {
169                         linklabel1.visible = false;
170                         label1.text = ltime.tostring();
171                     }
172                 };
173         }
174 
175         /// <summary>
176         /// 在textbox1文本框内点击回车的事件
177         /// </summary>
178         /// <param name="sender"></param>
179         /// <param name="e"></param>
180         private void textbox1_keydown(object sender, keyeventargs e)
181         {
182             //判断是否点击了回车按钮
183             if (e.keycode == keys.enter)
184             {
185                 //我这是把上面的复制下来了,直接查出结果
186                 if (dic.keys.contains(textbox1.text.trim()))
187                 {
188                     textbox2.text = dic[textbox1.text.trim()];
189                     linklabel1.visible = false;
190                     ltime = 0;
191                     label2.text = "您查询的结果:";
192                 }
193                 else
194                 {
195                     label2.text = "对不起,系统不包含您输入的单词";
196                     label1.text = "";
197                     textbox2.text = "";
198 
199                     linklabel1.visible = true;
200 
201                     linklabel1.text = "对不起请尝试使用(有道youdao)在线翻译:" + "\r\n\n\t" + textbox1.text.trim();
202 
203                     timer.stop();
204                     ltime = 0;
205                     linklabel1.bringtofront();
206                 }
207 
208             }
209         }
210     }
211 }

28.音乐播放器(winform)--------------这个软件会做了,才能代表c# winform开发 “基础”已经学会了

首先先上图片,了解一下软件的构造

         

  listbox控件属性要修改的地方

 

那些控件都好说,只要是播放控件vs上面没有:

这时,我们就要手动添加,相当于调用了windows的dll文件了

1、在vs工具箱里右键点击“组件”(这是我的习惯,点击别的也可以) 

2、找到“选择项”,点击。电脑一般配置的要等待一会,有点慢     

3、看图

       

 

form1主要部分:

form2主要部分:

            

   上代码了,接下来就自己对号入座吧

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.io;
 10 
 11 namespace 音乐播放器
 12 {
 13     public partial class frm_main : form
 14     {
 15         public frm_main()
 16         {
 17             initializecomponent();
 18         }
 19 
 20         #region 加载窗体
 21         private void frm_main_load(object sender, eventargs e)
 22         {
 23             trackbar1.sendtoback();//置于底层
 24             label1.image = image.fromfile("放音.jpg");
 25             label6.text = "25";
 26 
 27             //trackbar1.bringtofront();//置于顶层 
 28             //trackbar2.bringtofront();//置于顶层      
 29             //程序加载时,取消播放器的自动播放
 30             musicplayer.settings.autostart = false;
 31             label1.image = image.fromfile("放音.jpg");
 32             //autoellipsis 属性可以改变 label控件的大小
 33             tooltip1.settooltip(this.btn_playmode, "播放模式");//当鼠标放在控件上会显示  这是tooltip的功能
 34             tooltip1.settooltip(this.label1, "声音开关");//当鼠标放在控件上会显示  这是tooltip的功能
 35         }
 36         #endregion
 37 
 38         #region 窗体移动
 39         bool formmoveflag = false;//窗体是否移动标志位位
 40         point formpoint;//记录窗体的位置
 41         /// <summary>
 42         /// 鼠标在窗体上按下
 43         /// </summary>
 44         /// <param name="sender"></param>
 45         /// <param name="e"></param>
 46         private void mainform_mousedown(object sender, mouseeventargs e)
 47         {
 48             formpoint = new point();
 49             //   int xoffset;
 50             //   int yoffset;
 51             if (e.button == mousebuttons.left)//如果鼠标左键按下
 52             {
 53                 formpoint = new point(-e.x, -e.y); //得到变量的值
 54                 formmoveflag = true;//开始移动
 55             }
 56         }
 57         /// <summary>
 58         /// 鼠标在窗体上移动
 59         /// </summary>
 60         /// <param name="sender"></param>
 61         /// <param name="e"></param>
 62         private void mainform_mousemove(object sender, mouseeventargs e)
 63         {
 64             if (formmoveflag == true)//如果窗体正在移动
 65             {
 66                 point mousepos = control.mouseposition;//获取鼠标当前位置
 67                 mousepos.offset(formpoint.x, formpoint.y);//设置鼠标移动后的位置
 68                 location = mousepos;//将鼠标的坐标 传递给窗体
 69             }
 70         }
 71         /// <summary>
 72         /// 鼠标在窗体上释放
 73         /// </summary>
 74         /// <param name="sender"></param>
 75         /// <param name="e"></param>
 76         private void mainform_mouseup(object sender, mouseeventargs e)
 77         {
 78             if (e.button == mousebuttons.left)//按下的是鼠标左键
 79             {
 80                 formmoveflag = false;//停止移动
 81             }
 82         }
 83         #endregion
 84 
 85         #region 1、主要的播放功能
 86 
 87         //存储音乐文件的全路径
 88         list<string> listpath = new list<string>();
 89 
 90         #region 右键 打开添加音乐文件
 91         int addi = 0;
 92         private void btn_open_click(object sender, eventargs e)
 93         {
 94             openfiledialog ofd = new openfiledialog();
 95             ofd.initialdirectory = @"音乐加歌词";
 96             ofd.filter = "mp3文件|*.mp3|mp4文件|*.mp4|音乐文件|*.wav|所有文件|*.*";
 97             ofd.title = "请选择音乐文件";
 98             ofd.multiselect = true;//允许多选
 99             ofd.showdialog();
100 
101             //获得文本框中选择文件的全路径
102             string[] path = ofd.filenames;
103             for (int i = 0; i < path.length; i++)
104             {
105                 //将音乐文件的全路径加载到泛型集合中
106                 addi++;
107                 listpath.add(path[i]);
108                 //将音乐文件的文件名存储到listbox中
109                 lst_playerfile.items.add(addi + "、" + path.getfilename(path[i]));
110             }
111         }
112         #endregion
113         #region 右键删除
114         private void 删除toolstripmenuitem_click(object sender, eventargs e)
115         {
116             //删除的是列表中的选择项
117             //还要记住list集合也要删
118 
119             //获取要删除的歌曲的数量
120             int count = lst_playerfile.selecteditems.count;
121             for (int i = 0; i < count; i++)
122             {
123                 //先删除集合
124                 listpath.removeat(lst_playerfile.selectedindex);
125                 //再删除表
126                 lst_playerfile.items.removeat(lst_playerfile.selectedindex);
127             }
128         }
129         #endregion
130         #region 右键刷新
131         private void 刷新toolstripmenuitem_click(object sender, eventargs e)
132         {
133             int add = 0;
134             list<string> lst = new list<string>();
135 
136             for (int i = 0; i < lst_playerfile.items.count; i++)
137             {
138                 add++;
139                 //lst_playerfile.items.add(add + "、" + lst_playerfile.items[i]);
140                 string[] ss = lst_playerfile.items[i].tostring().split('、');
141                 lst.add(add + "、" + ss[1]);
142             }
143             lst_playerfile.items.clear();
144             foreach (var item in lst)
145             {
146                 lst_playerfile.items.add(item);
147             }
148             addi = add;//使刷新后的总行数等于addi,添加文件时可以正确排序
149         }
150         #endregion
151 
152         #region listbox的双击事件--选择播放的音乐
153         private void lst_playerfile_doubleclick(object sender, eventargs e)
154         {
155             //timer3.enabled = false;
156             //timer4.enabled = false;
157             try
158             {
159                 //索引找到点击播放的音乐是第几个
160                 musicplayer.url = listpath[lst_playerfile.selectedindex];
161                 musicplayer.ctlcontrols.play();
162                 isexistlrc(listpath[lst_playerfile.selectedindex]);
163                 btn_player.text = "暂停";
164                 index_dq = lst_playerfile.selectedindex;
165             }
166             catch { }
167         }
168         #endregion
169 
170         #region 播放按钮
171         bool bl = true;
172         private void btn_player_click(object sender, eventargs e)
173         {
174             try
175             {
176                 if (bl)
177                 {
178                     musicplayer.url = listpath[lst_playerfile.selectedindex];
179                     bl = false;
180                 }
181 
182                 if (lst_playerfile.selectedindex < 0)
183                 {
184                     messagebox.show("请选择播放的音乐文件");
185                     return;
186                 }
187                 if (btn_player.text == "播放")
188                 {
189                     //索引找到点击播放的音乐是第几个
190                     //musicplayer.url = listpath[lst_playerfile.selectedindex];
191                     musicplayer.ctlcontrols.play();
192                     //isexistlrc(listpath[lst_playerfile.selectedindex]);
193                     isexistlrc(musicplayer.url);
194                     for (int i = 0; i < listpath.count; i++)
195                     {
196                         if (musicplayer.url == listpath[i])
197                         {
198                             index_dq = i;
199                         }
200                     }
201                     //index_dq = lst_playerfile.selectedindex;
202                     //timer2.enabled = true;
203 
204                     btn_player.text = "暂停";
205                 }
206                 else if (btn_player.text == "暂停")
207                 {
208                     musicplayer.ctlcontrols.pause();
209                     btn_player.text = "播放";
210                 }
211             }
212             catch { }
213         }
214         #endregion
215         #region 终止播放 不是停止
216         private void btn_stop_click(object sender, eventargs e)
217         {
218             musicplayer.ctlcontrols.stop();
219         }
220         #endregion
221         #region 上一曲按钮
222         private void btn_shang_click(object sender, eventargs e)
223         {
224             //try
225             // {
226             int index = lst_playerfile.selectedindex;
227             lst_playerfile.selectedindices.clear();
228             index--;
229             if (index < -1)
230             {
231                 messagebox.show("选择播放文件");
232                 return;
233             }
234             else if (index < 0)
235             {
236                 index = listpath.count - 1;
237                 musicplayer.url = listpath[index];
238             }
239             musicplayer.url = listpath[index];
240             lst_playerfile.selectedindex = index;
241             musicplayer.ctlcontrols.play();
242             isexistlrc(listpath[lst_playerfile.selectedindex]);
243             // }
244             // catch { messagebox.show("选择播放文件"); }           
245         }
246         #endregion
247         #region 下一曲
248         private void btn_xia_click(object sender, eventargs e)
249         {
250             //try
251             //{
252             int index = lst_playerfile.selectedindex;
253             lst_playerfile.selectedindices.clear();
254 
255             if (index < 0)
256             {
257                 messagebox.show("选择播放文件");
258                 return;
259             }
260             index++;
261             if (index > listpath.count - 1)
262             {
263                 index = 0;
264                 musicplayer.url = listpath[index];
265             }
266             musicplayer.url = listpath[index];
267             lst_playerfile.selectedindex = index;
268             musicplayer.ctlcontrols.play();
269             isexistlrc(listpath[lst_playerfile.selectedindex]);
270             //}
271             //catch { messagebox.show("选择播放文件"); }
272         }
273         #endregion
274         #region 声音开关按键
275         private void label1_click(object sender, eventargs e)
276         {
277             //将label的tag属性设置为1
278             if (label1.tag.tostring() == "1")
279             {
280                 //目的让它静音
281                 musicplayer.settings.mute = true;
282                 label1.image = image.fromfile("静音.jpg");
283                 label1.tag = "2";
284                 label6.text = "0";//显示音量大小
285             }
286             else if (label1.tag.tostring() == "2")
287             {
288                 //放音
289                 musicplayer.settings.mute = false;
290                 label1.image = image.fromfile("放音.jpg");
291                 label1.tag = "1";
292                 label6.text = voice.tostring();
293             }
294         }
295         #endregion
296 
297         #region 模拟进度条--设置声音
298         int voice = 25;
299         //设置声音大小
300         public void setvoice(int voice)
301         {
302             if (voice >= 0 && voice <= 100)
303             {
304                 musicplayer.settings.volume = voice;
305                 label6.text = voice.tostring();
306             }
307         }
308         private void panel5_mousedown(object sender, mouseeventargs e)
309         {
310             if (e.location.x >= 0 && e.location.x <= 100)
311             {
312                 voice = e.location.x;
313                 panel5.size = new size(e.location.x, 3);
314                 setvoice(voice);
315             }
316         }
317         private void panel4_mousedown(object sender, mouseeventargs e)
318         {
319             if (e.location.x >= 0 && e.location.x <= 100)
320             {
321                 voice = e.location.x;
322                 setvoice(voice);
323                 panel5.size = new size(e.location.x, 3);
324             }
325         }
326         #endregion
327 
328         #region 计时器timer1--显示音乐时间、trackbar1显示播放进度
329         private void timer1_tick(object sender, eventargs e)
330         {
331             //如果播放器在播放中执行
332             if (musicplayer.playstate == wmplib.wmpplaystate.wmppsplaying)
333             {
334                 label3.text = musicplayer.currentmedia.duration.tostring() +
335                     "\r\n" + musicplayer.currentmedia.durationstring +
336                     "\r\n" + musicplayer.ctlcontrols.currentposition.tostring() +
337                     "\r\n" + musicplayer.ctlcontrols.currentpositionstring;
338 
339                 string[] sss1 = (musicplayer.currentmedia.duration.tostring()).split('.');
340                 string[] sss2 = (musicplayer.ctlcontrols.currentposition.tostring()).split('.');
341 
342                 trackbar1.maximum = int.parse(sss1[0]);
343                 trackbar1.value = int.parse(sss2[0]);
344 
345                 //if (convert.toint32(label1.tag) != 1)//当点击音乐开关时,label1.tag=2;
346                 //{
347                 //    label6.text = "0";//显示音量大小
348                 //}
349 
350                 if (loob)
351                 {
352                     //自动下一曲
353                     double d1 = double.parse(musicplayer.currentmedia.duration.tostring());
354 
355                     double d2 = double.parse(musicplayer.ctlcontrols.currentposition.tostring()) + 1;
356                     if (d1 <= d2)
357                     {
358                         //获得当前选中项的索引
359                         int index = lst_playerfile.selectedindex;
360 
361                         //清空所有选中项的索引
362                         lst_playerfile.selectedindices.clear();
363                         index_dq++;
364                         if (index_dq == lst_playerfile.items.count)
365                         {
366                             index_dq = 0;
367                         }
368                         //将改变后的索引重新的赋值给当前选中项的索引
369                         //if (index != index_dq)
370                         //{
371                         //    lst_playerfile.selectedindex = index;
372                         //}
373                         //else
374                         //{
375                         lst_playerfile.selectedindex = index_dq;
376                         //}
377                         musicplayer.url = listpath[index_dq];
378                         musicplayer.ctlcontrols.play();
379                         isexistlrc(listpath[index_dq]);
380                     }
381                 }
382             }
383         }
384         #endregion
385 
386         #endregion
387 
388         #region 2、歌词部分
389 
390         //存储时间
391         list<double> listtime = new list<double>();
392         //存储歌词
393         list<string> listlrctext = new list<string>();
394 
395         #region 添加歌词部分
396         //判断是否有歌词文件
397         void isexistlrc(string songpath)
398         {
399             //清空两个集合的内容
400             listtime.clear();
401             listlrctext.clear();
402 
403             songpath += ".lrc";
404             if (file.exists(songpath))
405             {
406                 //读取歌词文件
407                 string[] lrctext = file.readalllines(songpath, encoding.default);
408                 //格式化歌词
409                 formatlrc(lrctext);
410             }
411             else//不存在歌词
412             {
413                 label4.text = "---------歌词未找到---------";
414 
415                 form2.strlrc = label4.text;
416             }
417         }
418 
419         /// <summary>
420         /// 添加歌词
421         /// </summary>
422         /// <param name="lrctext"></param>
423         void formatlrc(string[] lrctext)
424         {
425             for (int i = 0; i < lrctext.length; i++)
426             {
427                 //lrc格式歌词是这样的:[00:15.57]当我和世界不一样
428                 string[] lrctemp = lrctext[i].split(new char[] { '[', ']' }, stringsplitoptions.removeemptyentries);
429                 //00:15.57   lrctemp[0]
430                 //当我和世界不一样 lrctemp[1]
431                 string[] lrcnewtemp = lrctemp[0].split(new char[] { ':' }, stringsplitoptions.removeemptyentries);
432                 //00 lrcnewtemp[0]
433                 //15.57 lrcnewtemp[1]
434                 double time = double.parse(lrcnewtemp[0]) * 60 + double.parse(lrcnewtemp[1]);
435                 //把截取出来的时间加到泛型集合中
436                 listtime.add(time);
437                 //把这个时间所对应的歌词存储到泛型集合中
438                 try
439                 {
440                     listlrctext.add(lrctemp[1]);
441                 }
442                 catch { listlrctext.add(lrctemp[0]); }
443             }
444         }
445         #endregion
446         #region 计时器timer2---播放歌词
447         private void timer2_tick(object sender, eventargs e)
448         {
449             for (int i = 0; i < listtime.count; i++)//listtime listlrctext都行
450             {
451                 try
452                 {
453                     if (musicplayer.ctlcontrols.currentposition >= listtime[i] && musicplayer.ctlcontrols.currentposition < listtime[i + 1])
454                     {
455                         label4.text = listlrctext[i];
456                         form2.strlrc = listlrctext[i];
457                     }
458                 }
459                 catch { label4.text = listlrctext[i]; }
460             }
461         }
462         #endregion
463 
464         #endregion
465 
466         #region 3、播放模式
467 
468         #region 之前写的按钮点击事件 音量加减、快进快退、快退不好使,查了资料还是不行,不知道是我写错了还是mp3格式不支持
469         //音量加
470         //private void btn_yl_jia_click(object sender, eventargs e)
471         //{           
472         //    musicplayer.settings.volume += 5;
473         //    // messagebox.show(musicplayer.settings.volume.tostring());
474         //}
475         //int t1 = 1;
476         //音量减
477         //private void btn_yl_jian_click(object sender, eventargs e)
478         //{
479         //    musicplayer.settings.volume -= 5;
480         //}
481         //快进
482         //private void btn_kj_click(object sender, eventargs e)
483         //{
484         //    if (t1 == 1)
485         //    {
486         //        musicplayer.ctlcontrols.fastforward();
487         //        t1 = 2;
488         //    }
489         //    else
490         //    {
491         //        musicplayer.ctlcontrols.play();
492         //        t1 = 1;
493         //    }
494         //}
495         //int t2 = 1;
496         //快退
497         //private void btn_kt_click(object sender, eventargs e)
498         //{
499         //    if (t2 == 1)
500         //    {
501         //        musicplayer.ctlcontrols.fastreverse();
502         //        t2 = 2;
503         //    }
504         //    else
505         //    {
506         //        musicplayer.ctlcontrols.play();
507         //        t2 = 1;
508         //    }
509         //}
510         #endregion
511 
512         #region 计时器timer3--关于播放模式(单曲循环)
513         private void timer3_tick(object sender, eventargs e)
514         {
515             if (musicplayer.playstate == wmplib.wmpplaystate.wmppsplaying)
516             {
517                 double d1 = double.parse(musicplayer.currentmedia.duration.tostring());
518                 double d2 = double.parse(musicplayer.ctlcontrols.currentposition.tostring()) + 1;
519                 if (d1 <= d2)
520                 {
521                     //获得当前选中项的索引
522                     int index = lst_playerfile.selectedindex;
523 
524                     //清空所有选中项的索引
525                     lst_playerfile.selectedindices.clear();
526 
527                     //将改变后的索引重新的赋值给当前选中项的索引
528                     if (index != index_dq)
529                     {
530                         lst_playerfile.selectedindex = index;//这里我写成index是因为 人性化些,歌曲是在单曲的但是你可以把索引放在别的文件上,不用让索引跳来挑去的
531 
532                     }
533                     else
534                     {
535                         lst_playerfile.selectedindex = index_dq;
536                     }
537                     musicplayer.url = listpath[index_dq];
538                     musicplayer.ctlcontrols.play();
539                     isexistlrc(listpath[index_dq]);
540                 }
541             }
542         }
543         #endregion
544 
545         #region 计时器timer4--关于播放模式(随机播放)
546         private void timer4_tick(object sender, eventargs e)
547         {
548             int i_lst = lst_playerfile.items.count - 1;
549             random ran = new random();
550             int index_t4 = lst_playerfile.selectedindex;
551 
552             if (musicplayer.playstate == wmplib.wmpplaystate.wmppsplaying)
553             {
554                 int vpc = ran.next(0, i_lst);
555                 double d1 = double.parse(musicplayer.currentmedia.duration.tostring());
556                 double d2 = double.parse(musicplayer.ctlcontrols.currentposition.tostring()) + 1;
557                 if (d1 <= d2)
558                 {
559                     //获得当前选中项的索引
560                     int index = vpc;
561                     //清空所有选中项的索引
562                     lst_playerfile.selectedindices.clear();
563                     //将索引赋值给当前选中项的索引
564                     //if (index_t4 != index_dq)
565                     //{
566                     lst_playerfile.selectedindex = index;//这里我写成index是因为 人性化些,歌曲是在单曲的但是你可以把索引放在别的文件上,不用让索引跳来挑去的
567                     index_dq = index;
568                     //}
569 
570                     musicplayer.url = listpath[index];
571                     musicplayer.ctlcontrols.play();
572                     isexistlrc(listpath[index]);
573                 }
574             }
575         }
576         #endregion
577 
578         #region 滚动播放进度条
579         private void trackbar1_scroll(object sender, eventargs e)
580         {
581             musicplayer.ctlcontrols.currentposition = trackbar1.value;
582         }
583         #endregion
584 
585         bool loob = true;
586 
587         #region 播放模式(单曲循环、顺序播放、随机播放、列表循环)
588         string strmucismode = "";
589         private void clearcheck()
590         {
591             单曲循环toolstripmenuitem1.checked = false;
592             顺序播放toolstripmenuitem1.checked = false;
593             随机播放toolstripmenuitem1.checked = false;
594             列表循环toolstripmenuitem1.checked = false;
595         }
596 
597         //播放模式的按钮
598         private void btn_playmode_click(object sender, eventargs e)
599         {
600             point p = new point(20, 0);
601             this.contextmenustrip2.show(btn_playmode, p);//定义相对于按钮的位置
602         }
603         int index_dq = 0;
604         private void 单曲循环toolstripmenuitem1_click(object sender, eventargs e)
605         {
606             loob = false;
607             strmucismode = "单曲循环";
608             clearcheck();
609             单曲循环toolstripmenuitem1.checked = true;
610             btn_playmode.image = image.fromfile(".//image/danqu.png");
611             tooltip1.settooltip(this.btn_playmode, "单曲循环");//当鼠标放在控件上会显示
612 
613             timer4.enabled = false;
614             timer3.enabled = true;
615         }
616         private void 顺序播放toolstripmenuitem1_click(object sender, eventargs e)
617         {
618             loob = true;
619             strmucismode = "顺序播放";
620             clearcheck();
621             顺序播放toolstripmenuitem1.checked = true;
622             btn_playmode.image = image.fromfile(".//image/shunxu.png");
623             tooltip1.settooltip(this.btn_playmode, "顺序播放");
624 
625             timer3.enabled = false;
626             timer4.enabled = false;
627         }
628         private void 随机播放toolstripmenuitem1_click(object sender, eventargs e)
629         {
630             loob = false;
631             strmucismode = "随机播放";
632             clearcheck();
633             随机播放toolstripmenuitem1.checked = true;
634             btn_playmode.image = image.fromfile(".//image/suiji.png");
635             tooltip1.settooltip(this.btn_playmode, "随机播放");
636 
637             btn_player.text = "暂停";
638             timer3.enabled = false;
639             timer4.enabled = true;
640         }
641 
642         //列表循环和顺序播放是一样的 我就写成一样的了
643         private void 列表循环toolstripmenuitem1_click(object sender, eventargs e)
644         {
645             loob = true;
646             strmucismode = "列表循环";
647             clearcheck();
648             列表循环toolstripmenuitem1.checked = true;
649             btn_playmode.image = image.fromfile(".//image/xunhuan.png");
650             tooltip1.settooltip(this.btn_playmode, "列表循环");
651 
652             timer3.enabled = false;
653             timer4.enabled = false;
654         }
655         #endregion
656 
657         #endregion
658 
659         #region 4、桌面效果(桌面歌词、最小化)
660 
661         #region 新建窗口form2 显示桌面歌词
662         form2 frm2 = form2.getsingle();
663         /// <summary>
664         /// 显示桌面歌词
665         /// </summary>
666         /// <param name="sender"></param>
667         /// <param name="e"></param>
668         private void btn_show_click(object sender, eventargs e)
669         {
670             if (btn_show.tag.tostring() == "show")
671             {
672                 btn_show.tag = "hide";
673                 tooltip1.settooltip(this.btn_show, "关闭桌面歌词");
674                 tooltip1.settooltip(this.lb_show, "关闭桌面歌词");
675                 frm2.show();
676             }
677             else
678             {
679                 btn_show.tag = "show";
680                 tooltip1.settooltip(this.btn_show, "显示桌面歌词");
681                 tooltip1.settooltip(this.lb_show, "显示桌面歌词");
682                 frm2.hide();//隐藏窗口  此处不能关闭,如果关闭后 由于form2窗体是单例模式创建的 一次只能创建一个 关闭后将无法打开
683             }
684         }
685         #endregion
686 
687         #region 最小化窗体 电脑右下角显示最小化图标
688         /// <summary>
689         /// 点击最小化按钮
690         /// </summary>
691         /// <param name="sender"></param>
692         /// <param name="e"></param>
693         private void btnmin_click(object sender, eventargs e)
694         {
695             if (this.windowstate != formwindowstate.minimized)
696             {
697                 this.hide();//隐藏窗口
698                 this.notifyicon1.visible = true;//右下角最小化图标可见
699                 this.notifyicon1.showballoontip(1000); //提示球 显示时间长度
700             }
701         }
702         /// <summary>
703         /// 双击电脑右下角程序图标
704         /// </summary>
705         /// <param name="sender"></param>
706         /// <param name="e"></param>
707         private void notifyicon1_mousedoubleclick(object sender, mouseeventargs e)
708         {
709             this.show();//显示窗体
710         }
711         //关闭窗口
712         private void btnexit_click(object sender, eventargs e)
713         {
714             this.close();
715         }
716         #endregion
717 
718         #endregion
719     }
720 }
721 
722 #region 网上对axwindowsmediaplayer1的 概述
723 //利用axwindowsmediaplayer(windows media player)制作mp3播放器 2 
724 //在制作mp3播放器之前,我们需要了解axwindowsmediaplayer 媒体主要方法属性:
725 //属性/方法名: 说明: 
726 //[基本属性]   
727 //url:string; 指定媒体位置,本机或网络地址 
728 //uimode:string; 播放器界面模式,可为full, mini, none, invisible 
729 //playstate:integer; 播放状态,1=停止,2=暂停,3=播放,6=正在缓冲,9=正在连接,10=准备就绪 
730 //enablecontextmenu:boolean; 启用/禁用右键菜单 
731 //fullscreen:boolean; 是否全屏显示 
732 ////播放器基本控制 
733 //ctlcontrols.play; 播放 
734 //ctlcontrols.pause; 暂停 
735 //ctlcontrols.stop; 停止 
736 //ctlcontrols.currentposition:double; 当前进度 
737 //ctlcontrols.currentpositionstring:string; 当前进度,字符串格式。如“00:23” 
738 //ctlcontrols.fastforward; 快进 
739 //ctlcontrols.fastreverse; 快退 
740 //ctlcontrols.next; 下一曲 
741 //ctlcontrols.previous; 上一曲 
742 //[settings] wmp.settings //播放器基本设置 
743 //settings.volume:integer; 音量,0-100 
744 //settings.autostart:boolean; 是否自动播放 
745 //settings.mute:boolean; 是否静音 
746 //settings.playcount:integer; 播放次数 
747 //[currentmedia] wmp.currentmedia //当前媒体属性 
748 //currentmedia.duration:double; 媒体总长度 
749 //currentmedia.durationstring:string; 媒体总长度,字符串格式。如“03:24” 
750 //currentmedia.getiteminfo(const string); 获取当前媒体信息"title"=媒体标题,"author"=艺术家,"copyright"=版权信息,"description"=媒体内容描述, "duration"=持续时间(秒),"filesize"=文件大小,"filetype"=文件类型,"sourceurl"=原始地址 
751 //currentmedia.setiteminfo(const string); 通过属性名设置媒体信息 
752 //currentmedia.name:string; 同 currentmedia.getiteminfo("title") 
753 //[currentplaylist] wmp.currentplaylist //当前播放列表属性 
754 //currentplaylist.count:integer; 当前播放列表所包含媒体数 
755 //currentplaylist.item[integer]; 获取或设置指定项目媒体信息,其子属性同wmp.currentmedia 
756 //axwindowsmediaplayer1.currentmedia.sourceurl; //获取正在播放的媒体文件的路径
757 //axwindowsmediaplayer1.currentmedia.name;          //获取正在播放的媒体文件的名称
758 //axwindowsmediaplayer1.ctlcontrols.play          播放 
759 //axwindowsmediaplayer1.ctlcontrols.stop          停止 
760 //axwindowsmediaplayer1.ctlcontrols.pause          暂停 
761 //axwindowsmediaplayer1.ctlcontrols.playcount        文件播放次数 
762 //axwindowsmediaplayer1.ctlcontrols.autorewind       是否循环播放 
763 //axwindowsmediaplayer1.ctlcontrols.balance         声道 
764 //axwindowsmediaplayer1.ctlcontrols.volume         音量 
765 //axwindowsmediaplayer1.ctlcontrols.mute          静音 
766 //axwindowsmediaplayer1.ctlcontrols.enablecontextmenu    是否允许在控件上点击鼠标右键时弹出快捷菜单 
767 //axwindowsmediaplayer1.ctlcontrols.animationatstart    是否在播放前先播放动画 
768 //axwindowsmediaplayer1.ctlcontrols.showcontrols      是否显示控件工具栏 
769 //axwindowsmediaplayer1.ctlcontrols.showaudiocontrols    是否显示声音控制按钮 
770 //axwindowsmediaplayer1.ctlcontrols.showdisplay       是否显示数据文件的相关信息 
771 //axwindowsmediaplayer1.ctlcontrols.showgotobar       是否显示goto栏 
772 //axwindowsmediaplayer1.ctlcontrols.showpositioncontrols  是否显示位置调节按钮 
773 //axwindowsmediaplayer1.ctlcontrols.showstatusbar      是否显示状态栏 
774 //axwindowsmediaplayer1.ctlcontrols.showtracker       是否显示进度条 
775 //axwindowsmediaplayer1.ctlcontrols.fastforward       快进 
776 //axwindowsmediaplayer1.ctlcontrols.fastreverse       快退 
777 //axwindowsmediaplayer1.ctlcontrols.rate          快进/快退速率 
778 //axwindowsmediaplayer1.allowchangedisplaysize 是否允许自由设置播放图象大小 
779 //axwindowsmediaplayer1.displaysize       设置播放图象大小 
780 //    1-mpdefaultsize         原始大小 
781 //    2-mphalfsize           原始大小的一半 
782 //    3-mpdoublesize          原始大小的两倍 
783 //    4-mpfullscreen          全屏 
784 //    5-mponesixteenthscreen      屏幕大小的1/16 
785 //    6-mponefourthscreen       屏幕大小的1/4 
786 //    7-mponehalfscreen        屏幕大小的1/2 
787 //axwindowsmediaplayer1.clicktoplay       是否允许单击播放窗口启动media player
788 //在视频播放之后,可以通过如下方式读取源视频的宽度和高度,然后设置其还原为原始的大小.
789 //         private void resizeoriginal()
790 //         {
791 //             int intwidth = axwindowsmediaplayer1.currentmedia.imagesourcewidth;
792 //             int intheight = axwindowsmediaplayer1.currentmedia.imagesourceheight;
793 //             axwindowsmediaplayer1.width = intwidth + 2;
794 //             axwindowsmediaplayer1.height = intheight + 2;
795 //         }
796 //打开媒体文件并播放:
797 //         dim filepath as string
798 //         with me.openfiledialog1
799 //             .title = "打开语音文件"
800 //             .checkpathexists = true
801 //             .checkfileexists = true
802 //             .multiselect = false
803 //             .filter = "mp3文件(*.mp3)|*.mp3|所有文件(*.*)|*.*"
804 //             if .showdialog = dialogresult.cancel then
805 //                 exit sub
806 //             end if
807 //             filepath = .filename
808 //         end with
809 //         me.text = "pc复读机-文件 " & filepath
810 //         axwindowsmediaplayer1.url = filepath
811 //         try
812 //             me.axwindowsmediaplayer1.ctlcontrols.play()
813 //         catch ex as exception
814 //             msgbox("对不起,不能播放此格式语音文件", msgboxstyle.okonly, "pc复读机")
815 //             exit sub
816 //         end try
817 //注意:
818 //axwindowsmediaplayer1.url 中url是表示要播放的文件名,取消了原来的name属性.
819 //axwindowsmediaplayer1.ctlcontrols.play()播放,同样还有pause,stop等其他属性.
820 //axwindowsmediaplayer1.settings.balance表示媒体播放的声道设置,0表示均衡,-1和1表示左右声道.
821 //axwindowsmediaplayer1.currentmedia.duration 表示要播放的文件的时间长度.可用它获取文件长度.
822 //axwindowsmediaplayer1.ctlcontrols.currentposition表示正在播放的文件的当前播放位置,可用这个属性来对媒体文件进行前进后退等设置.如
823 //axwindowsmediaplayer1.ctlcontrols.currentposition+1 表示前进1个时间单位.
824 //axwindowsmediaplayer1.settings.rate播放速率,一般乘以16后再显示kbps单位.
825 //注意:在上面程序中,如果在后面加上一个:
826 //msgbox(axwindowsmediaplayer1.currentmedia.duration.tostring )
827 //则显示结果很可能为0,因此,这时候很可能获取不到文件的播放时间长度,容易出错。所以在利用的时候可以加一个timer控件:
828 //private sub timer1_tick(byval sender as object, byval e as system.eventargs) handles timer1.tick
829 //         endpoint = axwindowsmediaplayer1.currentmedia.duration
830 //         if endpoint = 0 then exit sub '可能因为媒体文件的打开需要一定时间,这里等待媒体文件的打开
831 //         msgbox(axwindowsmediaplayer1.currentmedia.duration.tostring )
832 //end sub
833 //此时msgbox便会显示文件播放长度。
834 //2. ctlcontrols属性
835 //ctlcontrols属性是axwindowsmediaplayer的一个重要属性, 此控件中有许多常用成员。
836 //(1) 方法play
837 //用于播放多媒体文件,其格式为:
838 //窗体名.控件名.ctlcontrols.play()
839 //如: axwindowsmediaplayer1.ctlcontrols.play() ‘此处缺省窗体名是me
840 //(2) 方法pause
841 //用于暂停正在播放的多媒体文件,其格式为:
842 //窗体名.控件名.ctlcontrols.pause()
843 //如: axwindowsmediaplayer1.ctlcontrols.pause()
844 //(3) 方法stop
845 //用于停止正在播放的多媒体文件,其格式为:
846 //窗体名.控件名.ctlcontrols.stop()
847 //如: axwindowsmediaplayer1.ctlcontrols.stop()
848 //(4) 方法fastforward
849 //用于将正在播放的多媒体文件快进,其格式为:
850 //窗体名.控件名.ctlcontrols.fastforward()
851 //如: axwindowsmediaplayer1.ctlcontrols.forward()
852 //(5) 方法fastreverse
853 //窗体名.控件名.ctlcontrols.fastreverse()
854 //如: axwindowsmediaplayer1.ctlcontrols.fastreverse()
855 //6. 属性currentposition
856 //用于获取多媒体文件当前的播放进度,其值是数值类型,使用格式为:
857 //窗体名.控件名.ctlcontrols.currentposition
858 //d1 =axwindowsmediaplayer1.ctlcontrols.currentposition
859 //其中d1 是一个整型变量。
860 //7. 属性duration
861 //用于获取当前多媒体文件的播放的总时间,其值为数值类型,其使用格式为:
862 //窗体名.控件名.currentmedia.duration
863 //如:d2 =axwindowsmediaplayer1.currentmedia.duration
864 //其中d2是一个整型变量。
865 #endregion           
  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 
 10 namespace 音乐播放器
 11 {
 12     public partial class form2 : form
 13     {
 14         public form2()
 15         {
 16             initializecomponent();
 17         }
 18 
 19         #region 1、单例模式(只显示一个窗体)
 20         public static string strmusiclrc = " ";
 21 
 22         public static form2 frmsingle = null;//创建一个单例模式
 23 
 24         //提供一个静态方法  如果窗体未被创建则返回一个新窗体
 25         public static form2 getsingle()
 26         {
 27             if (frmsingle == null)
 28             {
 29                 frmsingle = new form2();
 30             }
 31             return frmsingle;
 32         }
 33         #endregion
 34 
 35         #region 2、设置from2 的起始位置
 36         private void form2_load(object sender, eventargs e)
 37         {
 38             this.location = new point(200, 600);//设置窗口出现的位置
 39 
 40             //以下两行代码可以将窗体设置为透明背景
 41             this.backcolor = color.black;
 42             this.transparencykey = this.backcolor;
 43         }
 44         #endregion
 45 
 46         #region 3、创建一个静态方法 通过静态方法进行歌词传递
 47         private static string _strlrc;
 48         public static string strlrc
 49         {
 50             get { return _strlrc; }
 51             set { _strlrc = value; }
 52         }
 53 
 54         //定时刷新歌词
 55         private void timer1_tick(object sender, eventargs e)
 56         {
 57             label1.text = strlrc;
 58         }
 59         #endregion
 60 
 61         #region 窗体移动
 62         bool formmoveflag = false;//窗体是否移动标志位位
 63         point formpoint;//记录窗体的位置
 64         /// <summary>
 65         /// 鼠标在窗体上按下
 66         /// </summary>
 67         /// <param name="sender"></param>
 68         /// <param name="e"></param>
 69         private void mainform_mousedown(object sender, mouseeventargs e)
 70         {
 71             formpoint = new point();
 72 
 73             if (e.button == mousebuttons.left)//如果鼠标左键按下
 74             {
 75                 formpoint = new point(-e.x, -e.y); //得到变量的值
 76                 formmoveflag = true;//开始移动
 77 
 78                 #region 还有种方法
 79                 //   int x;
 80                 //   int y;
 81                 //x = -e.x - systeminformation.framebordersize.width;//获取当前x坐标
 82                 //y = -e.y - systeminformation.captionheight - systeminformation.framebordersize.height;//获取当前y坐标
 83                 //formpoint = new point(x, y);
 84                 //formmove = true;//开始移动
 85                 #endregion
 86             }
 87         }
 88         /// <summary>
 89         /// 鼠标在窗体上移动
 90         /// </summary>
 91         /// <param name="sender"></param>
 92         /// <param name="e"></param>
 93         private void mainform_mousemove(object sender, mouseeventargs e)
 94         {
 95             if (formmoveflag == true)//如果窗体正在移动
 96             {
 97                 point mousepos = control.mouseposition;//获取鼠标当前位置
 98                 mousepos.offset(formpoint.x, formpoint.y);//设置鼠标移动后的位置
 99                 location = mousepos;//将鼠标的坐标 传递给窗体
100             }
101         }
102         /// <summary>
103         /// 鼠标在窗体上释放
104         /// </summary>
105         /// <param name="sender"></param>
106         /// <param name="e"></param>
107         private void mainform_mouseup(object sender, mouseeventargs e)
108         {
109             if (e.button == mousebuttons.left)//按下的是鼠标左键
110             {
111                 formmoveflag = false;//停止移动
112             }
113         }
114         #endregion
115     }
116 }

播放mp3的实体图:

 

播放mv的实体图:

   

二、线程

 1.创建线程_前台_后台_挂起_唤醒_阻塞_终止_优先级

  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 using system.threading;
  6 
  7 namespace 创建线程_前台_后台_挂起_唤醒_阻塞_终止_优先级
  8 {
  9     class program
 10     {
 11         static void main(string[] args)
 12         {
 13             //创建线程
 14             thread t1 = new thread(new threadstart(testmethod));
 15             thread t2 = new thread(new parameterizedthreadstart(testmethod));
 16             thread t3 = new thread(new threadstart(testmethod));
 17             thread t4 = new thread(new threadstart(s5000));
 18 
 19             //我把他们的排序从高到低----优先级
 20             //highest          在具有任何其他优先级的线程之前
 21             //abovenormal      可以将thread安排在具有highest优先级线程之后,在normal之前
 22             //normal           在abovenormal之后,belownormal之前。默认值。
 23             //belownormal      在normal之后,lowest之前            
 24             //lowest           在具有其他任何优先级的线程之后
 25 
 26             //priority属性来获取和设置其优先级
 27             t1.priority = threadpriority.highest;
 28             //t2.priority = threadpriority.abovenormal;
 29             //t3.priority = threadpriority.abovenormal;//可以不用写,这是默认的
 30             //t4.priority = threadpriority.abovenormal;
 31 
 32             #region 线程的前台、后台的区别
 33             //创建线程默认是前台的
 34             //当所有前台线程关闭时,所有的后台线程也会被直接终止,不会抛出异常。
 35             //当程序主线程被关闭时前台线程是不会关闭的,当前台线程全部结束后,整个程序结束
 36             t1.isbackground = true;//手动将前台线程改成后台线程isbackground
 37             t2.isbackground = true;
 38             //这时,t3,t4还是前台线程
 39             #endregion
 40 
 41             #region t1线程被挂起,唤醒。t2线程正常启动
 42             //!我学习这段时发现 挂起和唤醒已经过时了 不用怕,下面还有各种各样的线程锁
 43             t1.start();
 44             t1.suspend();//线程t1被挂起 -->suspend
 45             t2.start("hello");
 46             thread.sleep(1000);//使主线程休眠1s
 47             console.readkey();
 48             //在随便点击按钮后,线程t1被唤醒,恢复线程 -->resume
 49             t1.resume();
 50             #endregion
 51 
 52             #region 对中断、中止、终止的理解
 53             //中断 :计算机执行某程序时,发生了紧急事件或有特殊请求,中央处理机暂停某程序的执行,而去处理上述事件或请求,处理完毕后再重新执行某程序的过程。 
 54             //中止 :中途停止。 
 55             //终止 :结束;停止。
 56             #endregion
 57 
 58             #region abort和join的搭配使用
 59             //线程被终止,就停止运行,是无法恢复的,因为 windows 会永久地删除被中止线程的所有数据。            
 60             //1.abort()的功能是用来终止调用此方法的线程的,只是在多数情况下,
 61             //它需要一点时间,有些延迟(可能在短时间内此线程还在执行)...
 62             //2.join()方法它的功能不是终止线程,而是在t线程终止之前,阻止正在结束
 63             //(调用了abort()方法但还未结束)的t线程执行,同时使主线程等待,
 64             //直到t线程终止(也就是abort()方法终止过程完毕)了再执行下面的代码,
 65             //打印出来的结果,执行状态就为false,线程状态也为停止了
 66             t3.start();
 67             t3.abort(); //终止线程 使用abort()方法
 68             //t3.start();//线程正在运行或被终止;它无法重新启动。 这样是错误的
 69             console.writeline("线程t3被终止,按任意键继续");
 70             t3.join();//等待线程t3终止结束之后才能继续向下进行
 71             console.readkey();
 72             #endregion
 73 
 74             //join和sleep的区别
 75             t4.start();
 76             console.writeline("开始默念五个数");
 77             t4.join(); //阻塞 等待线程t4执行结束在执行下面的代码
 78             t4.join(5000);//他俩一样都是阻塞,这个只是阻塞5秒钟,不管t4线程有没有结束5s之后就继续向下执行,不要误解 在5s内t4线程结束了就会立即向下执行 这就是join和sleep的区别
 79 
 80             console.writeline(t1.name + "状态:" + t1.threadstate + " " + t1.isalive);
 81             console.writeline(t2.name + "状态:" + t2.threadstate + " " + t2.isalive);
 82             console.writeline(t3.name + "状态:" + t3.threadstate + " " + t3.isalive);
 83             console.writeline(t4.name + "状态:" + t4.threadstate + " " + t4.isalive);
 84             console.readkey();
 85         }
 86 
 87         public static void testmethod()
 88         {
 89             console.writeline("不带参数的线程");
 90         }
 91 
 92         public static void testmethod(object data)
 93         {
 94             string datastr = data as string;
 95             console.writeline("带参数的线程函数,参数为:{0}", datastr);
 96         }
 97 
 98         public static void s5000()
 99         {
100             thread.sleep(5000);//线程停留5秒
101         }
102     }
103 }

 2.同步

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 
 7 #region 同步和异步的区别
 8 ////同步、异步和并行的讲解:(百度上找的)
 9 ////假如5个菜分别是a,b,c,d,e  你有两个炉子  只能同时炒a跟b    
10 ////所以剩下的cde只能等ab炒完了才能开始  这个等待就是同步 我们叫做阻塞 即这个时候你只能做ab这两个菜
11 
12 ////假如你还有一台咖啡机, 你在炒ab的时候 把咖啡豆跟水放到咖啡机里打开开关  你就可以不用去管它了
13 ////我们说 我们新开了一个线程煮咖啡  但是注咖啡这个动作不妨碍你炒菜  所以煮咖啡这个线程是异步的 我们叫非阻塞
14 
15 ////等到咖啡机 叮---  告诉你咖啡煮好了  这个时候你去把咖啡拿出来   叮的这一声 我们叫通知 通知主线程也就是你 
16 ////我(咖啡机)的工作做完了,  你去把咖啡拿出来  我们叫回调 也就是 咖啡机线程完成之后 通知主线程要做的动作
17 
18 ////简单来讲  会占用你的时间 让你无法做其它事情的任务 叫同步任务(炒菜要专注 不然可能会糊锅)。
19 ////那些不需要占用你的时间的任务 叫异步任务  咖啡机自己会把咖啡煮好 不需要你一直看着它
20 
21 ////只有两个炉子,那就只能有2个人炒, 这个叫并行
22 #endregion
23 #region 注意这里manualresetevent和autoresetevent的一个重要区别:
24 //       manual的话肯定会给线程1和线程2都发送一个信号,而auto只会随机给其中一个发送信号。
25 
26 //为什么一个叫manual而一个叫auto呢?我想这是很多人的疑问,现在我们就来看这个问题。
27 //       刚才_manualresetevent .set();的这句话我想大家都明白了,可以看做将isrelease的属性设置为true.线程1中
28 // _manualresetevent.waitone();接收到信号后不再阻塞线程1。在此之后的整个过程中isrelease的值都是true.如果
29 //想将isrelease的值回复成false,就必须再调用_manualresetevent.reset()的方法。 
30 
31 //       如果是_autoresetevent.set(),那么_autoresetevent.waitone()后会自动将isrelease的值自动设置为false.
32 //这就是为什么一个叫auto,一个叫manual.
33 #endregion
34 
35 namespace 简单的同步
36 {
37     class program
38     {
39         static autoresetevent myresetevent = new autoresetevent(false);//默认阻塞当前线程
40         static autoresetevent changeevent = new autoresetevent(false);
41         //static manualresetevent myresetevent = new manualresetevent(false);//默认阻塞当前线程
42         //static manualresetevent changeevent = new manualresetevent(false);
43         static int number; //这是关键资源
44 
45         static void main()
46         {
47             thread paymoneythread = new thread(new threadstart(paymoneyproc));
48             //thread paymoneythread = new thread(paymoneyproc);//也可以写成这样
49             paymoneythread.name = "付钱线程";
50 
51             thread getbookthread = new thread(new threadstart(getbookproc));
52             getbookthread.name = "取书线程";
53 
54             paymoneythread.isbackground = true;
55             getbookthread.isbackground = true;
56 
57             paymoneythread.start();
58             getbookthread.start();
59 
60             for (int i = 1; i <= 10; i++)
61             {
62                 console.writeline("买书线程:数量{0}", i);//这个主线程运行的
63                 number = i;
64                 myresetevent.set();//发送信号
65                 //changeevent.set();
66                 thread.sleep(1000);
67             }
68             paymoneythread.abort();
69             getbookthread.abort();
70             console.readkey();
71         }
72 
73         static void paymoneyproc()
74         {
75             while (true)
76             {
77                 myresetevent.waitone();//接收信号
78                 //myresetevent.reset();
79                 console.writeline("{0}:数量{1}", thread.currentthread.name, number);
80                 changeevent.set();
81             }
82         }
83         static void getbookproc()
84         {
85             while (true)
86             {
87                 changeevent.waitone();
88                 //changeevent.reset();               
89                 console.writeline("{0}:数量{1}", thread.currentthread.name, number);
90                 console.writeline("------------------------------------------");
91                 //thread.sleep(0);
92             }
93         }
94     }
95 }
  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 using system.threading;
  6 
  7 //当要求使用volatile 声明的变量的值的时候,系统总是重新从它所在的内存读取数据,
  8 //即使它前面的指令刚刚从该处读取过数据。而且读取的数据立刻被保存。
  9 
 10 //调用getage()得到的是“主”内存区域的age数值。
 11 //用volatile修饰后的变量不允许有不同于“主”内存区域的变量拷贝。
 12 //换句话说,一个变量经volatile修饰后在所有线程中必须是同步的;
 13 //任何线程中改变了它的值,所有其他线程立即获取到了相同的值。
 14 //理所当然的,volatile修饰的变量存取时比一般变量消耗的资源要多一点;
 15 //因此线程有它自己的变量拷贝更为高效。 
 16 namespace volatile_同步
 17 {
 18     class program
 19     {
 20         static volatile int age = 10;//其实不加volatile输出也一样,有点抽象,内存内的值
 21 
 22         public static int getage1()
 23         {
 24             age = 20;
 25             return age;
 26         }
 27 
 28         public static int getage2()
 29         {
 30             age = 30;
 31             return age;
 32         }
 33 
 34         public static void age1()
 35         {
 36             for (int i = 0; i < 10; i++)
 37             {
 38                 thread.sleep(1000);
 39                 console.writeline("age1=" + age);
 40             }
 41         }
 42 
 43         static void main(string[] args)
 44         {
 45             thread t1 = new thread(age1);
 46             t1.isbackground = true;
 47             t1.start();
 48             thread.sleep(3000);
 49             getage1();
 50             thread.sleep(3000);//先运行一会getage1,在运行getage2
 51             getage2();//运行getage2时观察age1值变没?变了就是同步。
 52 
 53             console.read();
 54         }
 55     }
 56 }
 57 #region volatile的详解和与lock的不同
 58 //volatile多用于多线程的环境,当一个变量定义为volatile时,
 59 //读取这个变量的值时候每次都是从momery里面读取而不是从cache读。
 60 //这样做是为了保证读取该变量的信息都是最新的,而无论其他线程如何更新这个变量。
 61 
 62 // 更通俗的解释:
 63 //volatile 字面的意思时易变的,不稳定的。在c#中也差不多可以这样理解。
 64 //编译器在优化代码时,可能会把经常用到的代码存在cache里面,然后下一次调用就直接读取cache而不是内存,这样就大大提高了效率。但是问题也随之而来了。
 65 //在多线程程序中,如果把一个变量放入cache后,又有其他线程改变了变量的值,那么本线程是无法知道这个变化的。它可能会直接读cache里的数据。但是很不幸,cache里的数据已经过期了,读出来的是不合时宜的脏数据。这时就会出现bug。
 66 //用volatile声明变量可以解决这个问题。用volatile声明的变量就相当于告诉编译器,我不要把这个变量写cache,因为这个变量是可能发生改变的。
 67 
 68 //volatile解决问题1:cpu缓存
 69 //volatile解决问题2:编译器优化(指令乱序)
 70 
 71 //volatile 关键字表示字段可能被多个并发执行线程修改。声明为 volatile 的字段不受编译器优化(假定由单个线程访问)的限制。这样可以确保该字段在任何时间呈现的都是最新的值。
 72 //volatile 修饰符通常用于由多个线程访问而不使用 lock 语句(c# 参考) 语句对访问进行序列化的字段。有关在多线程方案中使用 volatile 的示例,请参见如何:创建和终止线程(c# 编程指南)。
 73 //volatile 关键字可应用于以下类型的字段:
 74 //引用类型。
 75 //指针类型(在不安全的上下文中)。请注意,虽然指针本身可以是可变的,但是它指向的对象不能是可变的。换句话说,您无法声明“指向可变对象的指针”。
 76 //整型,如 sbyte、byte、short、ushort、int、uint、char、float 和 bool。
 77 //具有整数基类型的枚举类型。
 78 //已知为引用类型的泛型类型参数。
 79 //intptr 和 uintptr。
 80 
 81 //volatile是最简单的一种同步方法,当然简单是要付出代价的。它只能在变量一级做同步,
 82 //volatile的含义就是告诉处理器, 不要将我放入工作内存, 请直接在主存操作我。
 83 //因此,当多线程同时访问该变量时,都将直接操作主存,从本质上做到了变量共享。
 84 
 85 
 86 //很有道理:::
 87 //c# volatile 与 lock
 88 //volatile的使用场景:多个线程同时访问一个变量,clr为了效率,允许每个线程进行本地缓存,
 89 //这就导致了变量的不一致性。volatile就是为了解决这个问题,volatile修饰的变量,
 90 //不允许线程进行本地缓存,每个线程的读写都是直接操作在共享内存上,
 91 //这就保证了变量始终具有一致性。缺点很明显:牺牲了效率。
 92 
 93 //lock的使用场景:多个线程同时访问一个代码块,使用lock 修饰该代码块,强制多个线程进行排队,
 94 //一个接一个的去访问。缺点很明显:排队进行必然导致效率低。
 95 
 96 //系统中应该尽量减少lock的使用(也就是排队执行的情况),因为根据阿姆达尔定律:
 97 //s=1/(a+(1-a)/n) ,其中s 为加速比,a 为串行计算部分,n为并行计算节点,该公式意味着:
 98 //如果具备足够的并行计算节点,要想增加系统的速度,必须减少串行部分。因为串行意味着,
 99 //一个人做的时候,其他人必须等着。google 的mapreduce,也就是把串行计算转化为并行计算。
100 #endregion
  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 using system.threading;
  6 
  7 //在这篇博客里学习的 http://www.cnblogs.com/zhycyq/articles/2679017.html
  8 namespace _3._1monitor_wait___pulse___pulseall__
  9 {
 10     class program
 11     {
 12         static void main(string[] args)
 13         {
 14             //开启三个线程
 15             new thread(a).start();
 16             new thread(b).start();
 17             new thread(c).start();
 18             console.readline();
 19         }
 20 
 21         //1.必须要先知道:object这是 .net framework 中所有类的最终基类
 22         //2.lock(object对象) 就是把.net framework 中所有类都加上锁了
 23         //三个进程中a没有睡眠直接进入就绪队列,b、c在外面(等待队列中),此时a是lockobj的拥有者
 24         //然后结果1s后a用pulus发出信号,允许第一个等待队列中的线程b进入就绪队列,线程b也是用pulus发出信号,使线程c进入了就绪队列。
 25         //线程a用wait放弃同步对象,进入了等待队列
 26         //此时就绪队列中线程b是lockobj的拥有者开始执行了
 27         //线程b结束后线程c拥有了lockobj使用权,开始执行
 28         //线程c结束了,同步对象闲置,a就重新得到了同步对象
 29         //线程a开始执行了
 30 
 31         //最后提醒一下,线程是没有先后顺序的,a先进入就绪队列获得拥有权这是一定的
 32         //接下来b和c不清楚是谁先进来的了,还有最后a和剩下的那个线程谁先得到拥有权也是未知的
 33         //上面的 解释方法思考
 34 
 35         static object lockobj = new object();
 36         static void a()
 37         {
 38             lock (lockobj) //线程a直接进入就绪队列 
 39             {
 40                 thread.sleep(1000);
 41                 monitor.pulse(lockobj);
 42                 monitor.wait(lockobj); //自我流放到等待队列
 43             }
 44             console.writeline("a exit...");
 45         }
 46         static void b()
 47         {
 48             thread.sleep(500);
 49             lock (lockobj) //线程b500ms后进入就绪队列
 50             {
 51                 monitor.pulse(lockobj);
 52             }
 53             console.writeline("b exit...");
 54         }
 55         static void c()
 56         {
 57             thread.sleep(800);
 58             lock (lockobj) //线程c800ms后进入就绪队列 
 59             { }
 60             console.writeline("c exit...");
 61         }
 62     }
 63 
 64     //下面的这个 和上面的这个思路差不多,就不解释了,用的是线程池
 65     //class mymanualevent
 66     //{
 67     //    private object lockobj = new object();
 68     //    private bool hasset = false;
 69     //    public void set()
 70     //    {
 71     //        lock (lockobj)
 72     //        {
 73     //            hasset = true;
 74     //            monitor.pulseall(lockobj);
 75     //        }
 76     //    }
 77     //    public void waitone()
 78     //    {
 79     //        lock (lockobj)
 80     //        {
 81     //            while (!hasset)
 82     //            {
 83     //                monitor.wait(lockobj);
 84     //            }
 85     //        }
 86     //    }
 87     //}
 88     //class program
 89     //{
 90     //    static mymanualevent mymanualevent = new mymanualevent();
 91     //    static void main(string[] args)
 92     //    {
 93     //        threadpool.queueuserworkitem(workerthread, "a");
 94     //        threadpool.queueuserworkitem(workerthread, "b");
 95     //        console.writeline("press enter to signal the green light");
 96     //        console.readline();
 97     //        mymanualevent.set();
 98     //        threadpool.queueuserworkitem(workerthread, "c");
 99     //        console.readline();
100     //    }
101     //    static void workerthread(object state)
102     //    {
103     //        mymanualevent.waitone();
104     //        console.writeline("thread {0} got the green light...", state);
105     //    }
106     //}
107 }
 1 using system;
 2 using system.collections;
 3 using system.collections.generic;
 4 using system.threading;
 5 
 6 //monitor类提供了与lock类似的功能,不过与lock不同的是,它能更好的控制同步块,
 7 //当调用了monitor的enter(object o)方法时,会获取o的独占权,直到调用exit(object o)方法时,
 8 //才会释放对o的独占权,可以多次调用enter(object o)方法,只需要调用同样次数的exit(object o)方法
 9 //即可,monitor类同时提供了tryenter(object o,[int])的一个重载方法,该方法尝试获取o对象的独占权,
10 //当获取独占权失败时,将返回false。
11 
12 //  但使用 lock 通常比直接使用 monitor 更可取,一方面是因为 lock 更简洁,
13 //另一方面是因为 lock 确保了即使受保护的代码引发异常,也可以释放基础监视器。
14 //这是通过 finally 中调用exit来实现的。事实上,lock 就是用 monitor 类来实现的。
15 //下面两段代码是等效的:
16 
17 //1.monitor.enter(object)方法是获取锁,monitor.exit(object)方法是释放锁,这就是monitor最常用的两个方法,当然在使用过程中为了避免获取锁之后因为异常,致锁无法释放,所以需要在try{} catch(){}之后的finally{}结构体中释放锁(monitor.exit())。
18 //2.monitor的常用属性和方法:
19 //    enter(object) 在指定对象上获取排他锁。
20 //    exit(object) 释放指定对象上的排他锁。
21 //    isentered 确定当前线程是否保留指定对象锁。
22 //    pulse 通知等待队列中的线程锁定对象状态的更改。
23 //    pulseall 通知所有的等待线程对象状态的更改。
24 //    tryenter(object) 试图获取指定对象的排他锁。
25 //    tryenter(object, boolean) 尝试获取指定对象上的排他锁,并自动设置一个值,指示是否得到了该锁。
26 //    wait(object) 释放对象上的锁并阻止当前线程,直到它重新获取该锁。
27 
28 //两个线程之间如何协同工作。
29 //这个程序的思路是共同做一件事情(从一个arraylist中删除元素),如果执行完成了,两个线程都停止执行。
30 
31 public class threaddemo
32 {
33     private thread threadone;
34     private thread threadtwo;
35     private arraylist stringlist;
36     private event eventhandler onnumberclear;//数据删除完成引发的事件
37     public static void main()
38     {
39         threaddemo demo = new threaddemo(1000);
40         demo.action();
41         console.writeline();
42         thread.sleep(10000);
43         console.readkey();
44     }
45     public threaddemo(int number)
46     {
47         random random = new random(1000000);
48         stringlist = new arraylist(number);
49         for (int i = 0; i < number; i++)
50         {
51             stringlist.add(random.next().tostring());
52         }
53         threadone = new thread(new threadstart(run));//两个线程共同做一件事情
54         threadtwo = new thread(new threadstart(run));//两个线程共同做一件事情
55         threadone.name = "线程1";
56         threadtwo.name = "线程2";
57         onnumberclear += new eventhandler(threaddemo_onnumberclear);
58     }
59     /// <summary>
60     /// 开始工作
61     /// </summary>
62     public void action()
63     {
64         threadone.start();
65         threadtwo.start();
66     }
67     /// <summary>
68     /// 共同做的工作
69     /// </summary>
70     private void run()
71     {
72         string stringvalue = null;
73         while (true)
74         {
75             monitor.enter(this);//锁定,保持同步
76             stringvalue = (string)stringlist[0];
77             console.writeline(thread.currentthread.name + "删除了" + stringvalue);
78             stringlist.removeat(0);//删除arraylist中的元素
79             if (stringlist.count == 0)
80             {
81                 onnumberclear(this, new eventargs());//引发完成事件
82             }
83             monitor.exit(this);//取消锁定
84             thread.sleep(5);
85         }
86     }
87 
88     //执行完成之后,停止所有线程
89     void threaddemo_onnumberclear(object sender, eventargs e)
90     {
91         console.writeline("执行完了,停止了所有线程的执行。");
92         threadtwo.abort();
93         threadone.abort();
94     }
95 }
  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 using system.threading;
  6 
  7 #region 一看就能懂 lock使用范围
  8 //lock:
  9 //class a
 10 //    {
 11 //    }
 12 //struct s
 13 //{
 14 //}
 15 //int i;
 16 //object o;
 17 //string str;
 18 //a a=new a();
 19 //s s=new s();
 20 //lock(i){}//错误
 21 //lock(o){}//正确
 22 //lock(str){}//正确
 23 //lock(a){}//正确
 24 //lock(s){}//错误
 25 #endregion
 26 
 27 #region 重点:
 28 //lock的参数必须是基于引用类型的对象,不要是基本类型像bool,int什么的,
 29 //这样根本不能同步,原因是lock的参数要求是对象,如果传入int,
 30 //势必要发生装箱操作,这样每次lock的都将是一个新的不同的对象。
 31 //最好避免使用public类型或不受程序控制的对象实例,因为这样很可能导致死锁。
 32 //特别是不要使用字符串作为lock的参数,因为字符串被clr“暂留”,
 33 //就是说整个应用程序中给定的字符串都只有一个实例,因此更容易造成死锁现象。
 34 //建议使用不被“暂留”的私有或受保护成员作为参数。其实某些类已经提供了专门用于被锁的成员,
 35 //比如array类型提供syncroot,许多其它集合类型也都提供了syncroot。
 36 // 所以,使用lock应该注意以下几点: 
 37 
 38 // 1、如果一个类的实例是public的,最好不要lock(this)。
 39 //因为使用你的类的人也许不知道你用了lock,如果他new了一个实例,
 40 //并且对这个实例上锁,就很容易造成死锁。
 41 
 42 // 2、如果mytype是public的,不要lock(typeof(mytype))
 43 
 44 // 3、永远也不要lock一个字符串
 45 #endregion
 46 //说明:
 47 // private static object  ojb = new object();
 48 //        lock(obj)
 49 //        {
 50 //                 //锁定运行的代码段
 51 //        }   
 52 //假设线程a先执行,线程b稍微慢一点。线程a执行到lock语句,判断obj是否已申请了互斥锁,
 53 //判断依据是逐个与已存在的锁进行object.referenceequals比较(此处未加证实),如果不存在,
 54 //则申请一个新的互斥锁,这时线程a进入lock里面了。
 55 //这时假设线程b启动了,而线程a还未执行完lock里面的代码。线程b执行到lock语句,
 56 //检查到obj已经申请了互斥锁,于是等待;直到线程a执行完毕,释放互斥锁,
 57 //线程b才能申请新的互斥锁并执行lock里面的代码。
 58 namespace _4.lock同步互斥锁
 59 {
 60     //为了能看的清楚一些,我是将两个线程分别执行两个方法,这两个方法调用同一个方法
 61     //测试lock能不能使一个进程执行时另一个线程等待,这时不确定两个线程哪个先启动的,没确定优先级
 62 
 63     #region 不加lock的输出
 64     //我是线程t2
 65     //我是线程t1
 66     //我是线程t1
 67     //我是线程t2
 68     //我是线程t2
 69     //我是线程t1
 70     //我是线程t1
 71     //我是线程t2
 72     //我是线程t2
 73     //我是线程t1
 74     //不加lock 输出的没有顺序,加入操作大文件更改或其他操作时很容易死锁
 75     #endregion
 76 
 77     #region 加lock的输出
 78     //我是线程t2
 79     //我是线程t2
 80     //我是线程t2
 81     //我是线程t2
 82     //我是线程t2
 83     //我是线程t1
 84     //我是线程t1
 85     //我是线程t1
 86     //我是线程t1
 87     //我是线程t1
 88     //加锁后多线程同步时不会产生死锁,一个线程执行时另一个线程在等待
 89     //别误会为什么是线程t2先执行的,可以想象好多人在跑步比赛,这是随机的
 90     #endregion
 91 
 92     partial class class1//我没有 写成public
 93     {
 94         //class1 c1 = new class1();//要用public 就实例化 使用lock(c1)
 95         public void t1(object tt1)
 96         {
 97             count(tt1);
 98         }
 99         public void t2(object tt2)
100         {
101             count(tt2);
102         }
103         public void count(object str)
104         {
105             lock (this)//不加锁直接把这段去掉
106                 for (int i = 0; i < 5; i++)
107                 {
108                     thread.sleep(500);
109                     console.writeline(str as string);
110                 }
111         }
112     }
113     class program
114     {
115         static void main(string[] args)
116         {
117             class1 c1 = new class1();
118             thread t1 = new thread(c1.t1);
119             thread t2 = new thread(c1.t2);
120 
121             t1.isbackground = true;
122             t2.isbackground = true;
123 
124             string str1 = "我是线程t1";
125             string str2 = "我是线程t2";
126 
127             t1.start(str1);
128             t2.start(str2);
129 
130             while (true)
131             {
132                 if (t1.isalive == true || t2.isalive == true)
133                 {
134                     //使主线程停顿一下,只是方便理解,不加这段也是一样的,
135                     //两个线程没执行完毕时主线程已经停在循环内了
136                     thread.sleep(1000);
137                 }
138                 else
139                     break;
140             }
141             console.writeline("回车,结束");
142             console.read();
143         }
144     }
145 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 //对于整数数据类型的简单操作,可以用 interlocked 类的成员来实现线程同步,
 6 //存在于system.threading命名空间。interlocked类有以下方法:increment , 
 7 //decrement , exchange 和compareexchange 。使用increment 和decrement 
 8 //可以保证对一个整数的加减为一个原子操作。exchange 方法自动交换指定变量的值。
 9 //compareexchange 方法组合了两个操作:比较两个值以及根据比较的结果将第三个值
10 //存储在其中一个变量中。比较和交换操作也是按原子操作执行的。
11 namespace _5.interlocked整数数据类型同步
12 {
13     class program
14     {
15         static void main(string[] args)
16         {
17             int i = 2;
18             system.threading.interlocked.increment(ref i);//递增i--> 2+1 = 3
19             console.writeline(i);
20             system.threading.interlocked.decrement(ref i);//递减i--> 3-1 = 2
21             console.writeline(i);
22             system.threading.interlocked.exchange(ref i, 100);//指定的值返回i=100
23             console.writeline(i);
24             system.threading.interlocked.compareexchange(ref i, 10, 100);//如果10和100是个相等的数就返回相同的那个数,不等就返回第一个数
25             console.writeline(i);
26 
27             console.read();
28         }
29     }
30 }
  1 using system;
  2 using system.collections.generic;
  3 using system.text;
  4 using system.threading;
  5 
  6 //下面是readerwriterlock类中的四个主要方法:
  7 //  a. acquirereaderlock(): 这个重载方法获取一个读者锁,接受一个整型或者timespan类型的timeout 值。timeout是一个检测死锁的利器。
  8 //  b. acquirewriterlock():  这个重载方法获取一个写者锁,接受一个整型或者timespan类型的timeout 值。
  9 //  c. releasereaderlock(): 释放读者锁。
 10 //  d. releasewriterlock(): 释放写者锁。
 11 
 12 //线程wt1 和 wt2 是writeints()方法中获得写锁的写者线程,线程rt1 和 rt2 是在readints()方法中
 13 //获得读者锁的读者线程。在writeints()方法中,变量x 和 y 的值分别被改成a 和 b. 当线程wt1 或
 14 //wt2 通过调用acquirewriterlock() 方法获得一个写者锁后,那么直到这个线程通过调用
 15 //releasewriterlock()方法释放锁之前任何其他线程(包括读者线程rt1 和 rt2)都不被允许访问相应对象。
 16 //这个行为与monitors类似 。在readints()方法中,线程rt1 和 rt2 通过调用acquirereaderlock()方法
 17 //获得读者锁, 这两个线程可以并发地访问变量x 和 y. 直到读者线程释放它们的读者锁以后,写者线程
 18 //(wt1 和 wt2)才被允许访问对应对象。只有读者线程在获得读者锁以后才可以并发地访问。
 19 
 20 //monitors类对于只想来读数据而非写数据来说过于“安全”了。monitors 也有一些性能问题,
 21 //对于只读类型的访问来说,性能瓶颈是可以避免的。readerwriterlock类通过允许任意数量的线程
 22 //并发地读取数据来提供一个解决数据读-写问题的完美方案。当线程更新数据时锁住数据。当没有
 23 //写者线程拥有锁的时候写者线程可以获得锁。写者锁可以在没有读者线程或者写者线程拥有锁的时候
 24 //获得锁。因此,readerwriterlock 就像是一段关键部分代码, 它也支持一个timeout 值,而这方面
 25 //在检测死锁时非常有用。
 26 namespace readwritelock
 27 {
 28     public class readwrite
 29     {
 30         private readerwriterlock rwl;
 31         private int x;
 32         private int y;
 33 
 34         public readwrite()
 35         {
 36             rwl = new readerwriterlock();
 37         }
 38 
 39         public void readints(ref int a, ref int b)
 40         {
 41             rwl.acquirereaderlock(timeout.infinite);
 42             try
 43             {
 44                 a = this.x;
 45                 b = this.y;
 46             }
 47             finally
 48             {
 49                 rwl.releasereaderlock();
 50             }
 51         }
 52 
 53         public void writeints(int a, int b)
 54         {
 55             rwl.acquirewriterlock(timeout.infinite);
 56             try
 57             {
 58                 this.x = a;
 59                 this.y = b;
 60                 console.writeline("x = " + this.x
 61                     + " y = " + this.y
 62                     + " threadid = " + thread.currentthread.gethashcode());
 63             }
 64             finally
 65             {
 66                 rwl.releasewriterlock();
 67             }
 68         }
 69     }
 70 
 71     public class rwapp
 72     {
 73         private readwrite rw = new readwrite();
 74 
 75         public static void main(string[] args)
 76         {
 77             rwapp e = new rwapp();
 78 
 79             thread wt1 = new thread(new threadstart(e.write));
 80             wt1.start();
 81             thread wt2 = new thread(new threadstart(e.write));
 82             wt2.start();
 83 
 84             thread rt1 = new thread(new threadstart(e.read));
 85             rt1.start();
 86             thread rt2 = new thread(new threadstart(e.read));
 87             rt2.start();
 88 
 89             console.readline();
 90         }
 91 
 92         private void write()
 93         {
 94             int a = 10;
 95             int b = 11;
 96             console.writeline("************** write *************");
 97 
 98             for (int i = 0; i < 5; i++)
 99             {
100                 this.rw.writeints(a++, b++);
101                 thread.sleep(1000);
102             }
103         }
104 
105         private void read()
106         {
107             int a = 10;
108             int b = 11;
109             console.writeline("************** read *************");
110 
111             for (int i = 0; i < 5; i++)
112             {
113                 this.rw.readints(ref a, ref b);
114                 console.writeline("for i = " + i
115                     + " a = " + a
116                     + " b = " + b
117                     + " theadid = " + thread.currentthread.gethashcode());
118                 thread.sleep(1000);
119             }
120         }
121     }
122 }
123 #region 拥有独占权的 写的时候 读要等待
124 //在考虑资源访问的时候,惯性上我们会对资源实施lock机制,但是在某些情况下,
125 //我们仅仅需要读取资源的数据,而不是修改资源的数据,在这种情况下获取资源的
126 //独占权无疑会影响运行效率,因此.net提供了一种机制,使用readerwriterlock进行
127 //资源访问时,如果在某一时刻资源并没有获取写的独占权,那么可以获得多个读的访问权,
128 //单个写入的独占权,如果某一时刻已经获取了写入的独占权,那么其它读取的访问权必须进行等待,
129 
130 //private static readerwriterlock m_readerwriterlock = new readerwriterlock();
131 //private static int m_int = 0;
132 //[stathread]
133 //static void main(string[] args)
134 //{
135 //thread readthread = new thread(new threadstart(read));
136 //readthread.name = "readthread1";
137 //thread readthread2 = new thread(new threadstart(read));
138 //readthread2.name = "readthread2";
139 //thread writethread = new thread(new threadstart(writer));
140 //writethread.name = "writerthread";
141 //readthread.start();
142 //readthread2.start();
143 //writethread.start();
144 //readthread.join();
145 //readthread2.join();
146 //writethread.join();
147 
148 //console.readline(); 
149 //}
150 //private static void read()
151 //{
152 //while (true)
153 //{
154 //console.writeline("threadname " + thread.currentthread.name + " acquirereaderlock");
155 //m_readerwriterlock.acquirereaderlock(10000);
156 //console.writeline(string.format("threadname : {0} m_int : {1}", thread.currentthread.name, m_int));
157 //m_readerwriterlock.releasereaderlock();
158 //}
159 //}
160 
161 //private static void writer()
162 //{
163 //while (true)
164 //{
165 //console.writeline("threadname " + thread.currentthread.name + " acquirewriterlock");
166 //m_readerwriterlock.acquirewriterlock(1000);
167 //interlocked.increment(ref m_int);
168 //thread.sleep(5000);
169 //m_readerwriterlock.releasewriterlock();
170 //console.writeline("threadname " + thread.currentthread.name + " releasewriterlock");
171 //}
172 //}
173 
174 //可以看到,当writerthread获取到写入独占权后,任何其它读取的线程都必须等待,
175 //直到writerthread释放掉写入独占权后,才能获取到数据的访问权,应该注意的是,
176 //上述打印信息很明显显示出,可以多个线程同时获取数据的读取权,
177 //这从readthread1和readthread2的信息交互输出可以看出。
178 #endregion
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.runtime.remoting.contexts;
 6 using system.threading;
 7 
 8 #region 详解
 9 //synchronizationattribute
10 //  当我们确定某个类的实例在同一时刻只能被一个线程访问时,我们可以直接将类标识成synchronization的,这样,clr会自动对这个类实施同步机制,实际上,这里面涉及到同步域的概念,当类按如下设计时,我们可以确保类的实例无法被多个线程同时访问
11 //  1). 在类的声明中,添加system.runtime.remoting.contexts.synchronizationattribute属性。
12 //    2). 继承至system.contextboundobject
13 //    需要注意的是,要实现上述机制,类必须继承至system.contextboundobject,换句话说,类必须是上下文绑定的。
14 //    一个示范类代码如下:
15 //[system.runtime.remoting.contexts.synchronization]
16 //public class synchronizedclass : system.contextboundobject
17 //{
18 
19 //}
20 #endregion
21 
22 //synchronizationattribute对于缺乏同步经验的程序员来说,使用起来很方便。
23 
24 namespace _9.synchronizationattribute多线程同步代码区
25 {
26     class program
27     {
28         static void main(string[] args)
29         {
30             sy c1 = new sy();
31             thread t1 = new thread(c1.t1);
32             thread t2 = new thread(c1.t2);
33 
34             t1.isbackground = true;
35             t2.isbackground = true;
36 
37             string str1 = "我是线程t1";
38             string str2 = "我是线程t2";
39 
40             t1.start(str1);
41             t2.start(str2);
42 
43             while (true)
44             {
45                 if (t1.isalive == true || t2.isalive == true)
46                 {
47                     //使主线程停顿一下,只是方便理解,不加这段也是一样的,
48                     //两个线程没执行完毕时主线程已经停在循环内了
49                     thread.sleep(1000);
50                 }
51                 else
52                     break;
53             }
54             console.writeline("回车,结束");
55             console.read();
56         }
57     }
58     [synchronization]
59     public class sy : contextboundobject  //上下文绑定
60     {
61         public void t1(object tt1)
62         {
63             count(tt1);
64         }
65         public void t2(object tt2)
66         {
67             count(tt2);
68         }
69         public void count(object str)
70         {
71             //lock (this)
72             //我之前写过的lock锁,不加lock两个线程会同时执行这个方法,很容易会死锁
73             //我这方法内容少,大内容就容易死锁了。
74             //这样对比就很明显了,不加lock线程也实现了同步,一个线程执行时另个一个线程等待
75             //这就是synchronizationattribute它的好处
76             for (int i = 0; i < 5; i++)
77             {
78                 thread.sleep(500);
79                 console.writeline(str as string);
80             }
81         }
82     }
83 }
  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.text;
  5 
  6 namespace _7._2mutex验证两个进程内的线程同时访问同一个资源
  7 {
  8     class program
  9     {
 10         static void main(string[] args)
 11         {
 12             #region 只能运行一个客户端程序
 13             bool flag = false;
 14             system.threading.mutex mutex = new system.threading.mutex(true, "test", out flag);
 15             //第一个参数:true--给调用线程赋予互斥体的初始所属权  
 16             //第一个参数:互斥体的名称  
 17             //第三个参数:返回值,如果调用线程已被授予互斥体的初始所属权,则返回true  
 18             if (!flag)
 19             {
 20                 console.writeline("只能运行一个客户端程序!");
 21                 console.read();
 22                 environment.exit(1);//退出程序  
 23             }
 24             #endregion  
 25 
 26             console.read();
 27         }
 28     }
 29 }
 30 
 31 //-------------------------------------------------------------
 32 using system;
 33 using system.collections.generic;
 34 using system.linq;
 35 using system.text;
 36 using system.threading;
 37 
 38 //c#语言有很多值得学习的地方,这里我们主要介绍c# mutex对象,包括介绍控制好多个线程相互之间的联系等方面。
 39 //如何控制好多个线程相互之间的联系,不产生冲突和重复,这需要用到互斥对象,即:system.threading 命名空间中的 mutex 类。
 40 //我们可以把mutex看作一个出租车,乘客看作线程。乘客首先等车,然后上车,最后下车。当一个乘客在车上时,其他乘客就只有
 41 //等他下车以后才可以上车。而线程与c# mutex对象的关系也正是如此,线程使用mutex.waitone()方法等待c# mutex对象被释放,
 42 //如果它等待的c# mutex对象被释放了,它就自动拥有这个对象,直到它调用mutex.releasemutex()方法释放这个对象,而在此期间,
 43 //其他想要获取这个c# mutex对象的线程都只有等待。
 44 //下面这个例子使用了c# mutex对象来同步四个线程,主线程等待四个线程的结束,而这四个线程的运行又是与两个c# mutex对象相关联的。
 45 //其中还用到autoresetevent类的对象,可以把它理解为一个信号灯。这里用它的有信号状态来表示一个线程的结束。
 46 
 47 #region 这个有些复杂 先不研究
 48 namespace threadexample
 49 {
 50     public class mutexsample
 51     {
 52         static mutex gm1;
 53         static mutex gm2;
 54         const int iters = 100;
 55         static autoresetevent event1 = new autoresetevent(false);
 56         static autoresetevent event2 = new autoresetevent(false);
 57         static autoresetevent event3 = new autoresetevent(false);
 58         static autoresetevent event4 = new autoresetevent(false);
 59 
 60         public static void main(string[] args)
 61         {
 62             console.writeline("mutex sample ");
 63             //创建一个mutex对象,并且命名为mymutex  
 64             gm1 = new mutex(true, "mymutex");
 65             //创建一个未命名的mutex 对象.  
 66             gm2 = new mutex(true);
 67             console.writeline(" - main owns gm1 and gm2");
 68 
 69             autoresetevent[] evs = new autoresetevent[4];
 70             evs[0] = event1; //为后面的线程t1,t2,t3,t4定义autoresetevent对象  
 71             evs[1] = event2;
 72             evs[2] = event3;
 73             evs[3] = event4;
 74 
 75             mutexsample tm = new mutexsample();
 76             thread t1 = new thread(new threadstart(tm.t1start));
 77             thread t2 = new thread(new threadstart(tm.t2start));
 78             thread t3 = new thread(new threadstart(tm.t3start));
 79             thread t4 = new thread(new threadstart(tm.t4start));
 80             t1.start();// 使用mutex.waitall()方法等待一个mutex数组中的对象全部被释放  
 81             t2.start();// 使用mutex.waitone()方法等待gm1的释放  
 82             t3.start();// 使用mutex.waitany()方法等待一个mutex数组中任意一个对象被释放  
 83             t4.start();// 使用mutex.waitone()方法等待gm2的释放  
 84 
 85             thread.sleep(2000);
 86             console.writeline(" - main releases gm1");
 87             gm1.releasemutex(); //线程t2,t3结束条件满足  
 88 
 89             thread.sleep(1000);
 90             console.writeline(" - main releases gm2");
 91             gm2.releasemutex(); //线程t1,t4结束条件满足  
 92 
 93             //等待所有四个线程结束  
 94             waithandle.waitall(evs);
 95             console.writeline(" mutex sample");
 96             console.readline();
 97         }
 98 
 99         public void t1start()
100         {
101             console.writeline("t1start started, mutex.waitall(mutex[])");
102             mutex[] gms = new mutex[2];
103             gms[0] = gm1;//创建一个mutex数组作为mutex.waitall()方法的参数  
104             gms[1] = gm2;
105             mutex.waitall(gms);//等待gm1和gm2都被释放  
106             thread.sleep(2000);
107             console.writeline("t1start finished, mutex.waitall(mutex[]) satisfied");
108             event1.set(); //线程结束,将event1设置为有信号状态  
109         }
110         public void t2start()
111         {
112             console.writeline("t2start started, gm1.waitone( )");
113             gm1.waitone();//等待gm1的释放  
114             console.writeline("t2start finished, gm1.waitone( ) satisfied");
115             event2.set();//线程结束,将event2设置为有信号状态  
116         }
117         public void t3start()
118         {
119             console.writeline("t3start started, mutex.waitany(mutex[])");
120             mutex[] gms = new mutex[2];
121             gms[0] = gm1;//创建一个mutex数组作为mutex.waitany()方法的参数  
122             gms[1] = gm2;
123             mutex.waitany(gms);//等待数组中任意一个mutex对象被释放  
124             console.writeline("t3start finished, mutex.waitany(mutex[])");
125             event3.set();//线程结束,将event3设置为有信号状态  
126         }
127         public void t4start()
128         {
129             console.writeline("t4start started, gm2.waitone( )");
130             gm2.waitone();//等待gm2被释放  
131             console.writeline("t4start finished, gm2.waitone( )");
132             event4.set();//线程结束,将event4设置为有信号状态  
133         }
134     }
135 }
136 #endregion
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 using system.runtime.compilerservices;
 7 
 8 #region 讲解
 9 //methodimplattribute
10 //如果临界区是跨越整个方法的,也就是说,整个方法内部的代码都需要上锁的话,
11 //使用methodimplattribute属性会更简单一些。这样就不用在方法内部加锁了,
12 //只需要在方法上面加上 [methodimpl(methodimploptions.synchronized)] 就可以了,
13 //mehthodimpl和methodimploptions都在命名空间system.runtime.compilerservices 里面。
14 //但要注意这个属性会使整个方法加锁,直到方法返回,才释放锁。因此,使用上不太灵活。
15 //如果要提前释放锁,则应该使用monitor或lock。
16 #endregion
17 
18 //我这人比较懒,我还是用lock那个试验来说明如何给方法加锁的
19 namespace _10.methodimplattribute给方法加锁
20 {
21     partial class class1//我没有 写成public
22     {
23         //class1 c1 = new class1();//要用public 就实例化 使用lock(c1)
24         public void t1(object tt1)
25         {
26             count(tt1);
27         }
28         public void t2(object tt2)
29         {
30             count(tt2);
31         }
32 
33         //首先先确定了,要被多个线程访问的共同方法。就是他
34         //然后在该方法头上写上[methodimpl(methodimploptions.synchronized)]
35         //这样就可以去掉lock锁了,结果是一样的
36         [methodimpl(methodimploptions.synchronized)]
37         public void count(object str)
38         {
39             //lock (this)
40             for (int i = 0; i < 5; i++)
41             {
42                 thread.sleep(500);//可以不写。为了看效果用的
43                 console.writeline(str as string);
44             }
45         }
46     }
47 
48     class program
49     {
50         static void main(string[] args)
51         {
52             class1 c1 = new class1();
53             thread t1 = new thread(c1.t1);
54             thread t2 = new thread(c1.t2);
55 
56             t1.isbackground = true;
57             t2.isbackground = true;
58 
59             string str1 = "我是线程t1";
60             string str2 = "我是线程t2";
61 
62             t1.start(str1);
63             t2.start(str2);
64 
65             while (true)
66             {
67                 if (t1.isalive == true || t2.isalive == true)
68                 {
69                     //使主线程停顿一下,只是方便理解,不加这段也是一样的,
70                     //两个线程没执行完毕时主线程已经停在循环内了
71                     thread.sleep(1000);
72                 }
73                 else
74                     break;
75             }
76             console.writeline("回车,结束");
77             console.read();
78         }
79     }
80 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 //用lock和monitor可以很好地起到线程同步的作用,但它们无法实现线程之间传递事件。
 7 //如果要实现线程同步的同时,线程之间还要有交互,就要用到同步事件。
 8 //同步事件是有两个状态(终止和非终止)的对象,它可以用来激活和挂起线程。
 9 
10 //autoresetevent自动变为非终止,就是说一个autoresetevent只能激活一个线程。
11 namespace _12.同步事件autoresetevent_线程之间传递事件_
12 {
13     class program
14     {
15         const int numiterations = 5;
16 
17         static autoresetevent myresetevent = new autoresetevent(false);
18         static int number;
19         static void main()
20         {
21             thread myreaderthread1 = new thread(new threadstart(myreadthreadproc1));
22             thread myreaderthread2 = new thread(new threadstart(myreadthreadproc2));
23             myreaderthread1.name = "readerthread1";
24             myreaderthread2.name = "readerthread2";
25             myreaderthread1.start();
26             myreaderthread2.start();
27             for (int i = 1; i <= numiterations; i++)
28             {
29                 console.writeline("writer thread writing value: {0}", i);
30                 number = i;
31                 // 发信号,说明值已经被写进去了。这里的意思是说set是一个发信号的方法。
32                 myresetevent.set();
33                 myresetevent.set();
34                 //怕会误会“是不是就发了一个信号,才一个线程接到的”,我这发两个信号,结果在下面
35                 #region 这我就不多解释了,仔细想想就明白了,两个信号不一定是哪个线程接受到了(包括重复接收)
36                 //writer thread writing value: 1
37                 //readerthread2 reading value: 1
38                 //writer thread writing value: 2
39                 //readerthread2 reading value: 2
40                 //readerthread1 reading value: 2
41                 //writer thread writing value: 3
42                 //readerthread2 reading value: 3
43                 //writer thread writing value: 4
44                 //readerthread2 reading value: 4
45                 //readerthread1 reading value: 4
46                 //writer thread writing value: 5
47                 //readerthread2 reading value: 5
48                 #endregion
49                 //事实证明autoresetevent的特性,不可以写成多发信号,只有一对一
50 
51                 thread.sleep(1000);
52             }
53             myreaderthread1.abort();
54             myreaderthread2.abort();
55 
56             console.read();
57 
58             #region 结果是不固定的 我收集了一份,一看便知道autoresetevent它的特点了
59             //它发送的信号,只有一个能接收到,不会启动多个线程
60 
61             //writer thread writing value: 1
62             //readerthread1 reading value: 1
63             //writer thread writing value: 2
64             //readerthread1 reading value: 2
65             //writer thread writing value: 3
66             //readerthread2 reading value: 3
67             //writer thread writing value: 4
68             //readerthread2 reading value: 4
69             //writer thread writing value: 5
70             //readerthread1 reading value: 5
71             #endregion
72         }
73         static void myreadthreadproc1()
74         {
75             while (true)
76             {
77                 //在数据被作者写入之前不会被读者读取
78                 myresetevent.waitone();//接受到信号后,代表 写完可以看了
79                 //还有一点就是:收到信号后会自动关闭信号
80                 console.writeline("{0} reading value: {1}", thread.currentthread.name, number);
81                 //myresetevent.reset();//将其设置为无信号//已经无信号了,可以不用写
82             }
83         }
84 
85         static void myreadthreadproc2()
86         {
87             while (true)
88             {
89                 //声明一下:autoresetevent里没有waitany和waitall方法
90                 //在数据被作者写入之前不会被读者读取
91                 myresetevent.waitone();//接受到信号后,代表 写完可以看了
92                 console.writeline("{0} reading value: {1}", thread.currentthread.name, number);
93             }
94         }
95     }
96 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 
 7 //将autoresetevent里的代码改成下面这样子
 8 namespace _12.同步事件manualresetevent__线程之间传递事件一对多_
 9 {
10     class program
11     {
12         const int numiterations = 5;
13 
14         static manualresetevent mymanualresetevent = new manualresetevent(false);
15         static int number;
16         static void main()
17         {
18             thread myreaderthread1 = new thread(new threadstart(myreadthreadproc1));
19             thread myreaderthread2 = new thread(new threadstart(myreadthreadproc2));
20             myreaderthread1.name = "readerthread1";
21             myreaderthread2.name = "readerthread2";
22             myreaderthread1.start();
23             myreaderthread2.start();
24             for (int i = 1; i <= numiterations; i++)
25             {
26                 console.writeline("writer thread writing value: {0}", i);
27                 number = i;
28                 // 发信号,说明值已经被写进去了。这里的意思是说set是一个发信号的方法。
29                 mymanualresetevent.set();//发送信号,两个线程都会收到信号
30 
31                 thread.sleep(1000);
32             }
33             myreaderthread1.abort();
34             myreaderthread2.abort();
35 
36             console.read();
37         }
38         static void myreadthreadproc1()
39         {
40             while (true)
41             {
42                 //在数据被作者写入之前不会被读者读取
43                 mymanualresetevent.waitone();//接受到信号后,代表 写完可以看了
44                 console.writeline("{0} reading value: {1}", thread.currentthread.name, number);
45                 mymanualresetevent.reset();//将其设置为无信号          
46             }
47         }
48 
49         static void myreadthreadproc2()
50         {
51             while (true)
52             {
53                 //在数据被作者写入之前不会被读者读取
54                 mymanualresetevent.waitone();//接受到信号后,代表 写完可以看了
55                 //还有一点就是:收到信号后会不自动关闭信号
56                 console.writeline("{0} reading value: {1}", thread.currentthread.name, number);
57                 mymanualresetevent.reset();//将其设置为无信号      
58             }
59         }
60     }
61 }

 3.线程池

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 
 7 //它有一些限制: 
 8 //1. 线程池中所有线程都是后台线程,如果进程的所有前台线程都结束了,所有的后台线程就会停止。不能把入池的线程改为前台线 程。 
 9 //2. 不能给入池的线程设置优先级或名称。 
10 //3. 对于com对象,入池的所有线程都是多线程单元(multi-threaded apartment,mta)线程。许多com对象都需要单线程单元(single -threaded apartment,sta)线程。 
11 //4.入池的线程只能用于时间较短的任务。如果线程要一直运行(如word的拼写检查器线程),就应使用thread类创建一个线程。
12 //这是个简单的线程池操作,可以扩展利用多线程的同步,异步
13 //由于线程的创建和销毁需要耗费一定的开销,过多的使用线程会造成内存资源的浪费,出于对性能的考虑,
14 //于是引入了线程池的概念。线程池维护一个请求队列,线程池的代码从队列提取任务,然后委派给线程池
15 //的一个线程执行,线程执行完不会被立即销毁,这样既可以在后台执行任务,又可以减少线程创建和销毁
16 //所带来的开销。
17 
18 //线程池线程默认为后台线程(isbackground)。
19 namespace 线程池
20 {
21     class program
22     {
23         static void main(string[] args)
24         {
25             //将工作项加入到线程池队列中,这里可以传递一个线程参数
26             threadpool.queueuserworkitem(testmethod, "hello");
27             thread.sleep(1000);
28 
29             console.readkey();
30         }
31 
32         public static void testmethod(object data)
33         {
34             string datastr = data as string;
35             console.writeline(datastr);
36         }
37     }
38 }

4.异步

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 
 7 namespace 异步1.线程池异步
 8 {
 9     class program
10     {
11         public static void mymethoda()
12         {
13             for (int i = 0; i < 3; i++)
14             {
15                 console.writeline("我是mymethoda" + i);
16             }
17         }
18         public static void mymethodb()
19         {
20             for (int i = 0; i < 3; i++)
21             {
22                 console.writeline("我是mymethodb" + i);
23             }
24         }
25 
26         static void main(string[] args)
27         {
28             using (manualresetevent m1 = new manualresetevent(false))
29             using (manualresetevent m2 = new manualresetevent(false))
30             {
31                 threadpool.queueuserworkitem(delegate
32                 {
33                     mymethoda();
34                     m1.set();
35                 });
36                 threadpool.queueuserworkitem(delegate
37                 {
38                     mymethodb();
39                     m2.set();
40                 });
41                 waithandle.waitall(new waithandle[] { m1, m2, });
42                 #region 看两次输出的结果,可以看出是异步进行的
43                 //1.
44                 //我是mymethoda0
45                 //我是mymethodb0
46                 //我是mymethodb1
47                 //我是mymethodb2
48                 //我是mymethoda1
49                 //我是mymethoda2
50                 //2.
51                 //我是mymethoda0
52                 //我是mymethoda1
53                 //我是mymethodb0
54                 //我是mymethodb1
55                 //我是mymethodb2
56                 //我是mymethoda2
57                 #endregion
58             }
59             console.read();
60         }
61     }
62 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 using system.threading;
 7 //task 的优点以及功能
 8 //1、在任务启动后,可以随时以任务延续的形式注册回调。
 9 //2、通过使用 continuewhenall 和 continuewhenany 方法或者 waitall 方法或 waitany 方法,协调多个为了响应 begin_ 方法而执行的操作。
10 //3、在同一task 对象中封装异步 i/o 绑定和计算绑定操作。
11 //4、监视task 对象的状态。
12 //5、使用taskcompletionsource 将操作的状态封送到task 对象。
13 namespace 异步2.task_异步等待_wait_waitall_waitany
14 {
15     class program
16     {
17         public static void mymethoda()
18         {
19             for (int i = 0; i < 5; i++)
20             {
21                 console.writeline(datetime.now.tostring());
22                 thread.sleep(1000);
23             }
24         }
25         public static void mymethodb()
26         {
27             for (int i = 0; i < 5; i++)
28             {
29                 console.writeline(datetime.now.tostring());
30                 thread.sleep(1000);
31             }
32         }
33 
34         static void main(string[] args)
35         {
36             task t1 = new task(mymethoda);//也可以这么写都是一样的,前提要加上t1.start()才能执行
37             task t2 = task.factory.startnew(delegate { mymethodb(); });
38             t1.start();
39             //它是一个一个的等待结束
40             //t1.wait();
41             //t2.wait();
42 
43             //这是同时进行的异步.先把上面的两行注释掉
44             //等待对象完成执行过程
45             task.waitall(t1, t2);
46             //task.waitany(t1, t2);//等待一个线程结束
47             console.writeline("主线程已结束");
48             console.read();
49 
50             #region 不加wait、waitall会怎样输出
51             //主线程已结束
52             //2016/12/8 9:52:34
53             //2016/12/8 9:52:34
54             //2016/12/8 9:52:35
55             //2016/12/8 9:52:35
56             //2016/12/8 9:52:36
57             //2016/12/8 9:52:36
58             //2016/12/8 9:52:37
59             //2016/12/8 9:52:37
60             //2016/12/8 9:52:38
61             //2016/12/8 9:52:38
62 
63             //加上它还是有好处的
64             #endregion
65         }
66     }
67 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 
 7 namespace 异步3.task捕获异常
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             task t1 = new task(mymethod);
14             t1.start();
15             t1.wait();
16             //发生一个或多个错误
17             //原因我告诉你:
18             //task的异常会重新抛到wait和allwait中
19             //捕获异常方法很简单还记得try catch吧,把t1.wait()写成下面的这样就行了
20             //try { t1.wait();} catch (exception e) { console.writeline(e); }
21 
22             console.writeline("主线程代码运行结束");
23             console.readline();
24         }
25 
26         static void mymethod()
27         {
28             throw new exception("task异常测试");
29             //点击运行时会在这里报异常,因为这是自己设置的异常,不用管他,点击f5继续
30             //你会发现异常停在了t1.wait()位置
31         }
32     }
33 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 
 7 namespace 异步4.task返回值
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             task<int> task = new task<int>(() =>
14             {
15                 int sum = 0;
16                 console.writeline("使用task执行异步操作.");
17                 for (int i = 0; i < 100; i++)
18                 {
19                     sum += i;
20                 }
21                 return sum;
22             });
23             //启动任务,并安排到当前任务队列线程中执行任务(system.threading.tasks.taskscheduler)
24             task.start();
25 
26             console.writeline("主线程执行其他处理");
27             //等待任务的完成执行过程。
28             task.wait();
29             //获得任务的执行结果
30             console.writeline("任务执行结果:{0}", task.result.tostring());
31 
32             console.read();
33         }
34     }
35 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 using system.threading.tasks;
 7 
 8 //使用cancellationtokensource对象需要与task对象进行配合使用,task会对当前运行的状态进行控制
 9 //(这个不用我们关心是如何孔控制的)。而cancellationtokensource则是外部对task的控制,
10 //如取消、定时取消。
11 
12 //task.factory.startnew 创建并启动了 mytask 方法,并传递了一个 cancellationtokensource.token 
13 //对象进去。我们可以通过在外部cancellationtokensource对象进行控制是否取消任务的运行。
14 //当在 mytask 中的 canceltokensource.iscancellationrequested 判断如果是取消了任务的话 
15 //就跳出while循环执行。也就结束了任务
16 namespace 异步5.cancellationtokensource_终止线程
17 {
18     class program
19     {
20         //声明cancellationtokensource对象
21         static cancellationtokensource canceltokensource = new cancellationtokensource();
22 
23         //程序入口
24         static void main(string[] args)
25         {
26             ;
27             task.factory.startnew(mytask, canceltokensource.token);
28 
29             console.writeline("请按回车键(enter)停止");
30             console.readline();
31 
32             canceltokensource.cancel();
33 
34             console.writeline("已停止");
35             console.readline();
36         }
37 
38         //测试方法
39         static void mytask()
40         {
41             //判断是否取消任务
42             while (!canceltokensource.iscancellationrequested)
43             {
44                 console.writeline(datetime.now);
45                 thread.sleep(1000);
46             }
47         }
48     }
49 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 using system.threading.tasks;
 7 
 8 namespace 异步5._2.cancellationtokensource_终止多个线程
 9 {
10     class program
11     {
12         //声明cancellationtokensource对象
13         static cancellationtokensource c1 = new cancellationtokensource();
14         static cancellationtokensource c2 = new cancellationtokensource();
15         static cancellationtokensource c3 = new cancellationtokensource();
16 
17         //使用多个cancellationtokensource进行复合管理
18         static cancellationtokensource compositecancel = cancellationtokensource.createlinkedtokensource(c1.token, c2.token, c3.token);
19 
20         //程序入口
21         static void main(string[] args)
22         {
23             //task.factory.startnew(mytask, compositecancel.token);
24             task.factory.startnew(mytask1, c1.token);
25             task.factory.startnew(mytask2, c2.token);
26             task.factory.startnew(mytask3, c3.token);
27 
28             console.writeline("请按回车键(enter)停止");
29             console.readline();
30 
31             //任意一个 cancellationtokensource 取消任务,那么所有任务都会被取消。
32             c1.cancel();
33 
34             console.writeline("已停止");
35             console.readline();
36         }
37 
38         //测试方法
39         static void mytask1()
40         {
41             //判断是否取消任务
42             while (!compositecancel.iscancellationrequested)
43             {
44                 console.writeline("c1");
45                 thread.sleep(1000);
46             }
47         }
48         static void mytask2()
49         {
50             //判断是否取消任务
51             while (!compositecancel.iscancellationrequested)
52             {
53                 console.writeline("c2");
54                 thread.sleep(1000);
55             }
56         }
57         static void mytask3()
58         {
59             //判断是否取消任务
60             while (!compositecancel.iscancellationrequested)
61             {
62                 console.writeline("c3");
63                 thread.sleep(1000);
64             }
65         }
66     }
67 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 //在使用能够task类的wait方法等待一个任务时或派生类的result属性获得任务
 7 //执行结果都有可能阻塞线程,为了解决这个问题可以使用continuewith方法,
 8 //他能在一个任务完成时自动启动一个新的任务来处理执行结果。
 9 namespace _6.continuewith方法在任务完成时启动一个新任务
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             //创建一个任务
16             task<int> task = new task<int>(() =>
17             {
18                 int sum = 0;
19                 console.writeline("使用task执行异步操作.");
20                 for (int i = 0; i < 100; i++)
21                 {
22                     sum += i;
23                 }
24                 return sum;
25             });
26             //启动任务,并安排到当前任务队列线程中执行任务(system.threading.tasks.taskscheduler)
27             task.start();
28             console.writeline("主线程执行其他处理");
29             #region 解释这段的意思
30             //我来详细的解释下这个地方:
31             //    1.先明确上面task创建的线程和主线程都在开始工作
32             //    2.我想得到task任务运行结果,假如我直接写个方法输出它的结果
33             //        想象一下,假如task任务还没结束你就要输出它的结果了
34             //        那结果能准确吗?
35             //        假如我不用方法输出它的结果,我建个线程来输出它的结果
36             //            想象一下,task任务和新建的线程同时运行中,
37             //            一个在时时刻刻更新数据一个在时时刻刻读出它的数据
38             //            相当于两个线程撞车了,阻塞。
39             //    用到continuewith方法来解决这个问题 
40             //continuewith方法在任务完成时启动一个新任务
41             #endregion
42             //任务完成时执行处理。
43             task cwt = task.continuewith(t =>
44             {
45                 console.writeline("任务完成后的执行结果:{0}", t.result.tostring());
46             });
47             console.read();
48         }
49     }
50 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 using system.threading.tasks;
 7 
 8 namespace 异步7.task内taskfactory类_创建一组具有相同状态的任务_
 9 {
10     class program
11     {
12         static cancellationtokensource cts = new cancellationtokensource();
13         //我们还可以使用计时取消任务,当一个任务超过了我们所设定的时间然后自动取消该任务的执行
14         //把上面的一行注释掉换成下面的这一样,会发现3s后自动停止
15         //static cancellationtokensource cts = new cancellationtokensource(3000);
16         //前提要在.net4.5之上的版本,我的是.net4.0 我使用不了
17 
18         static void main(string[] args)
19         {
20             string s1 = datetime.now.tostring("mmss");//yyyy-mm-dd  hh24:mm:ss
21             string s2 = string.empty;
22             task parent = new task(() =>
23             {
24                 //cancellationtokensource cts = new cancellationtokensource(5000);
25 
26                 //创建任务工厂
27                 taskfactory tf = new taskfactory(cts.token, taskcreationoptions.attachedtoparent, taskcontinuationoptions.executesynchronously, taskscheduler.default);
28                 //添加一组具有相同状态的子任务
29                 task[] task = new task[]{
30             tf.startnew(() => { console.writeline("我是任务工厂里的第一个任务。"); }),
31             tf.startnew(() => { console.writeline("我是任务工厂里的第二个任务。"); }),
32             tf.startnew(() => { console.writeline("我是任务工厂里的第三个任务。"); }),
33             tf.startnew(() => { for (int i = 0; i < 10; i++)//这个区间大于5s,看看能不能自动关闭
34             {
35                 if(!cts.iscancellationrequested)//千万不要忘了写这句
36                 {
37                     console.writeline("已经运行"+i+"s");
38                     thread.sleep(1000);
39                 }
40             } })
41         };
42             });
43             parent.start();
44 
45             //.net4.0不支持定时操作,我自己写个定时关闭
46             while (true)
47             {
48                 s2 = datetime.now.tostring("mmss");
49                 int i = int.parse(s2) - int.parse(s1);
50 
51                 if (i > 5)//运行时间规定5s钟,超时自动关闭
52                 {
53                     cts.cancel();
54                     console.writeline("已经运行" + i + "s" + " 用时超过5s" + " 5s后将自动关闭系统");
55 
56                     thread.sleep(5000);
57                     break;
58                     #region 运行结果
59                     //已经运行0s
60                     //我是任务工厂里的第一个任务。
61                     //我是任务工厂里的第二个任务。
62                     //我是任务工厂里的第三个任务。
63                     //已经运行1s
64                     //已经运行2s
65                     //已经运行3s
66                     //已经运行4s
67                     //已经运行5s
68                     //已经运行6s 用时超过5s 5s后将自动关闭系统
69                     #endregion
70                 }
71             }
72         }
73     }
74 }
  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.threading.tasks;
 10 using system.threading;
 11 
 12 #region 不会
 13 //任务内部实现和任务调度
 14 
 15 //1、任务内部有一组构成任务状态的属性,标识任务的唯一id、表示任务的执行状态(taskstatus)、任务创建时提供的回调函数的引用和传递给回调函数的数据对象asyncstate、对任务创建时的任务调度对象(taskscheduler)的引用、对父任务的引用以及对执行上下文的引用和manualreseteventslim对象的引用。
 16 //2、task类和task<tresult>类都实现了标准的释放资源的接口,允许在任务完成处理的时候使用dispose方法释放资源(关闭manualreseteventslim对象实例)。
 17 //3、可以使用task类的currentid属性获得正在执行的任务的id,如果没有任务在执行currentid返回值为null,currentid是一个int?可空类型的属性。
 18 //4、任务执行的生命周期通过taskstatus类型的一个值来表示,taskstatus所包含的值:
 19 
 20 
 21 //public enum taskstatus
 22 //{
 23 //     created = 0,
 24 //     waitingforactivation = 1,
 25 //     waitingtorun = 2,
 26 //     running = 3,
 27 //     waitingforchildrentocomplete = 4,
 28 //     rantocompletion = 5,
 29 //     canceled = 6,
 30 //     faulted = 7,
 31 //}
 32 
 33 //5、在任务内部由taskscheduler类调度任务的执行,该类是一个抽象类,fcl中从他派生了两个派生类:
 34 //threadpooltaskscheduler线程池任务调度器
 35 //所有任务默认都是采用threadpooltaskscheduler调度任务,他是采用线程池来执行任务,可以通过taskscheduler类的静态属性default获得对默认任务调度器的引用。
 36 //synchronizationcontexttaskscheduler同步上下文任务调度器
 37 //synchronizationcontexttaskscheduler任务调度器能够用在window form、wpf等应用程序,他的任务调度是采用的gui线程,所以他能同步更新ui组件,可以通过taskscheduler类的静态方法fromcurrentsynchronizationcontext获得对一个同步上下文任务调度起的引用。
 38 //6、例如
 39 
 40 
 41 //private void button1_click(object sender, eventargs e)
 42 //{
 43 //    //获得同步上下文任务调度器
 44 //    taskscheduler m_synccontexttaskscheduler = taskscheduler.fromcurrentsynchronizationcontext();
 45 
 46 //    //创建任务,并采用默认任务调度器(线程池任务调度器)执行任务
 47 //    task<int> task = new task<int>(() =>
 48 //    {
 49 //       //执行复杂的计算任务。
 50 //       thread.sleep(2000);
 51 //       int sum = 0;
 52 //       for (int i = 0; i < 100; i++)
 53 //       {
 54 //           sum += i;
 55 //       }
 56 //       return sum;
 57 //     });
 58 //     var cts=new cancellationtokensource();
 59 //     //任务完成时启动一个后续任务,并采用同步上下文任务调度器调度任务更新ui组件。
 60 //     task.continuewith(t => {this.label1.text="采用synchronizationcontexttaskscheduler任务调度器更新ui。\\r\\n计算结果是:"+task.result.tostring(); },
 61 //                cts.token ,taskcontinuationoptions.attachedtoparent,m_synccontexttaskscheduler);
 62 //             task.start();
 63 //        }
 64 #endregion
 65 
 66 namespace windowsformsapplication1
 67 {
 68     public partial class form1 : form
 69     {
 70         public form1()
 71         {
 72             initializecomponent();
 73         }
 74 
 75         static cancellationtokensource cts;
 76         private void button1_click(object sender, eventargs e)
 77         {
 78             label1.text = "";
 79             //获得同步上下文任务调度器
 80             taskscheduler m_synccontexttaskscheduler = taskscheduler.fromcurrentsynchronizationcontext();
 81 
 82             //创建任务,并采用默认任务调度器(线程池任务调度器)执行任务
 83             task<int> task = new task<int>(() =>
 84             {
 85                 //执行复杂的计算任务。
 86                 thread.sleep(2000);
 87                 int sum = 0;
 88                 for (int i = 0; i < 1000; i++)
 89                 {
 90                     sum += i;
 91                 }
 92                 return sum;
 93             });
 94             var cts = new cancellationtokensource();
 95             //任务完成时启动一个后续任务,并采用同步上下文任务调度器调度任务更新ui组件。
 96             task.continuewith(t => { this.label1.text = "采用synchronizationcontexttaskscheduler任务调度器更新ui。\\r\\n计算结果是:" + task.result.tostring(); },//this.label1.text="采用synchronizationcontexttaskscheduler任务调度器更新ui。\\r\\n计算结果是:"+task.result.tostring();
 97                        cts.token, taskcontinuationoptions.attachedtoparent, m_synccontexttaskscheduler);
 98             task.start();
 99         }
100     }
101 }

 三、进程

进程简单操作:

1.查找进程_结束进程

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.diagnostics;
 6 using system.threading;
 7 
 8 namespace 查找进程_结束进程
 9 {
10     class program
11     {
12         static int ii = 0;
13         static void main(string[] args)
14         {
15             process[] pro = process.getprocesses();//获取已开启的所有进程
16             //可以改成坑人程序,把所有的进程全部关闭
17             //遍历所有查找到的进程
18             for (int i = 0; i < pro.length; i++)
19             {
20                 //判断此进程是否是要查找的进程
21                 if (string.compare(pro[i].processname.tostring(), "想要结束的进程", true) == 0)
22                 {//compare是不区分大小写的
23                     pro[i].kill();//结束进程
24                     console.writeline("进程结束");
25                     ii++;
26                 }
27             }
28             if (ii == 0)
29             {
30                 console.writeline("没有这个进程");
31             }
32             console.read();
33         }
34     }
35 }

2. 进程打开指定文件

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.diagnostics;
 6 
 7 namespace 进程打开指定文件
 8 {
 9     class program
10     {
11         static void main(string[] args)
12         {
13             //processstartinfo psi = new processstartinfo("字符串的知识.txt");
14             //process p = new process();
15             //p.startinfo = psi;
16             //p.start();
17 
18             //这两种是一样的,下面的这个比较简单一些
19             //process p;//实例化一个process对象
20             //p = process.start("字符串的知识.txt");//要开启的进程(或 要启用的程序),括号内为绝对路径
21 
22             //我个人喜欢这么写,比较懒
23             //process.start("字符串的知识.txt");
24             //打开我的vs软件
25             process.start(@"d:\program files (x86)\microsoft visual studio 10.0\common7\ide\devenv.exe");
26 
27             //p.kill();//结束进程
28         }
29     }
30 }

 进程间通信:

 1.自定义消息进程间通信

  1)、一个项目上的多进程通信

     

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.runtime.interopservices;
 10 using system.diagnostics;
 11 
 12 #region 简单介绍下 0x0400
 13 // 我们不仅可以传递系统已经定义好的消息,还可以传递自定义的消息(只需要发送消息端和
 14 //接收消息端对自定义的消息值统一即可)。下面的发送和接收端同时演示了系统消息和自定义的消息。
 15 //消息统一采用4位16进制的数。
 16 //系统消息使用的是0x0100(wm_keydown);0x0000--0x0400是系统自定义的消息,其中0x0000为wm_null,
 17 //0x0400为wm_user。0x0400以后的数值我们可以作为自定义的消息值。
 18 
 19 //简单记法:0x0400是个分界值,小于它是系统自定义的消息,大于它是用户自定义消息!!
 20 #endregion
 21 
 22 namespace 消息传递_发_
 23 {
 24     public partial class form1 : form
 25     {
 26         public form1()
 27         {
 28             initializecomponent();
 29         }
 30 
 31         [dllimport("user32.dll", entrypoint = "sendmessage")]
 32         private static extern int sendmessage(intptr hwnd, int msg, int wparam, int lparam);
 33 
 34         processstartinfo startinfo = new processstartinfo();
 35         process pro = new process();
 36 
 37         private void button1_click(object sender, eventargs e)
 38         {
 39             startinfo.filename = @"消息传递(接).exe";
 40             pro.startinfo = startinfo;
 41             pro.start();
 42         }
 43 
 44         private void button2_click(object sender, eventargs e)
 45         {
 46             pro.kill();
 47         }
 48 
 49         //系统消息0x0100
 50         //不知道对不对,错误了,请提醒
 51         /*是系统发出来的消息,感觉很奇怪明明是自己输入的值
 52         其实这输入完,点击“发送(系统消息)”时,系统利用这个窗体的句柄
 53         把点击过的按键都存储了起来。将这一串键盘值组织成一个字符串*/
 54         private void button3_click(object sender, eventargs e)
 55         {
 56             intptr hwnd = pro.mainwindowhandle;
 57             int data = convert.toint32(this.textbox1.text);
 58 
 59             sendmessage(hwnd, 0x0100, data, 0);
 60         }
 61 
 62         //自己自定义的消息 大于0x0400
 63         /* 这有个弯好好想,这是自己定义的消息,在“消息传递(接).exe”程序里
 64         重写了接收处理函数defproc,当发送出去的数字,重写的方法里都会响应到。
 65         不要迷茫为什么这个就是自己自定义消息,上面的是系统消息,因为0x0400是个分界值*/
 66         private void button4_click(object sender, eventargs e)
 67         {
 68             intptr hwnd = pro.mainwindowhandle;
 69             int data = convert.toint32(this.textbox1.text);
 70 
 71             //sendmessage(hwnd, message.wm_test, data, 0);
 72             sendmessage(hwnd, message.wm_test, data, 0);
 73         }
 74     }
 75     class message
 76     {
 77         public const int user = 0x0400;
 78         //刚开始我也很纳闷,为什么都是固定的16进制呢,我上网一查,原来固定的值有256个,我给复制在下方了
 79         public const int wm_test = user + 101;
 80         public const int wm_msg = user + 102;
 81     }
 82 }
 83 #region  c#sendmessage用法
 84 // 函数功能:该函数将指定的消息发送到一个或多个窗口。此函数为指定的窗口调用窗口程序,直到窗口程序处理完消息再返回。该函数是应用程序和应用程序之间进行消息传递的主要手段之一。
 85 //    函数原型:lresult sendmessage(hwnd hwnd,uint msg,wparam wparam,lparam iparam);
 86 
 87 //    参数:
 88 
 89 //    hwnd:其窗口程序将接收消息的窗口的句柄。如果此参数为hwnd_broadcast,则消息将被发送到系统中所有顶层窗口,包括无效或不可见的非自身拥有的窗口、被覆盖的窗口和弹出式窗口,但消息不被发送到子窗口。
 90 
 91 //    msg:指定被发送的消息。
 92 
 93 //    wparam:指定附加的消息指定信息。
 94 
 95 //    iparam:指定附加的消息指定信息。
 96 
 97 //    返回值:返回值指定消息处理的结果,依赖于所发送的消息。
 98 
 99 //    备注:需要用hwnd_broadcast通信的应用程序应当使用函数registerwindowmessage来为应用程序间的通信取得一个唯一的消息。
100 
101 //    如果指定的窗口是由调用线程创建的,则窗口程序立即作为子程序调用。如果指定的窗口是由不同线程创建的,则系统切换到该线程并调用恰当的窗口程序。线程间的消息只有在线程执行消息检索代码时才被处理。发送线程被阻塞直到接收线程处理完消息为止。
102 
103 //c#中使用该函数首先导入命名空间:
104 //using system.runtime.interopservices;
105 
106 //然后写api引用部分的代码,放入 class 内部
107 //[dllimport("user32.dll", entrypoint = "sendmessage")]
108 // private static extern int sendmessage(intptr hwnd, int wmsg, int wparam, int lparam);
109 
110 //这个函数有四个参数,第一个是窗口句柄,窗口可以是任何类型的屏幕对象;第二个是用于区别其他消息的常量值;第三个通常是一个与消息有关的常量值,也可能是窗口或控件的句柄,第三个参数是可选参数,有的消息要,有的不需要,比如单击就不需要这个参数,
111 // 别的消息,比如鼠标移动的可能需要在这里加上一些鼠标的参数;第四个通常是一个指向内存中数据的指针。在c#中消息需要定义成windows系统中的原始的16进制数字,比如 const int wm_lbutton = 0x201; //定义了鼠标的左键点击消息。详细值在最后。
112 
113 //例如:
114 //const int bm_click = 0xf5;
115 // intptr maindhwnd = findwindow(null, "qq用户登录"); //获得qq登陆框的句柄
116 //if (maindhwnd != intptr.zero)
117 // {
118 //     intptr childhwnd = findwindowex(maindhwnd, intptr.zero, null, "登录");   //获得按钮的句柄
119 //    if (childhwnd != intptr.zero)
120 //     {
121 //         sendmessage(childhwnd, bm_click, 0, 0);     //发送点击按钮的消息
122 //    }
123 //     else
124 //     {
125 //         messagebox.show("没有找到子窗口");
126 //     }
127 // }
128 //else
129 // {
130 //     messagebox.show("没有找到窗口");
131 // } 
132 
133 //wmsg参数常量值:
134 
135 // //创建一个窗口   
136 //const int wm_create = 0x01;   
137 // //当一个窗口被破坏时发送   
138 //const int wm_destroy = 0x02;   
139 // //移动一个窗口   
140 //const int wm_move = 0x03;   
141 // //改变一个窗口的大小   
142 //const int wm_size = 0x05;   
143 // //一个窗口被激活或失去激活状态   
144 //const int wm_activate = 0x06;   
145 // //一个窗口获得焦点   
146 //const int wm_setfocus = 0x07;   
147 // //一个窗口失去焦点   
148 //const int wm_killfocus = 0x08;   
149 // //一个窗口改变成enable状态   
150 //const int wm_enable = 0x0a;   
151 // //设置窗口是否能重画   
152 //const int wm_setredraw = 0x0b;   
153 // //应用程序发送此消息来设置一个窗口的文本   
154 //const int wm_settext = 0x0c;   
155 // //应用程序发送此消息来复制对应窗口的文本到缓冲区   
156 //const int wm_gettext = 0x0d;   
157 // //得到与一个窗口有关的文本的长度(不包含空字符)   
158 //const int wm_gettextlength = 0x0e;   
159 // //要求一个窗口重画自己   
160 //const int wm_paint = 0x0f;   
161 // //当一个窗口或应用程序要关闭时发送一个信号   
162 //const int wm_close = 0x10;   
163 // //当用户选择结束对话框或程序自己调用exitwindows函数   
164 //const int wm_queryendsession = 0x11;   
165 // //用来结束程序运行   
166 //const int wm_quit = 0x12;   
167 // //当用户窗口恢复以前的大小位置时,把此消息发送给某个图标   
168 //const int wm_queryopen = 0x13;   
169 // //当窗口背景必须被擦除时(例在窗口改变大小时)   
170 //const int wm_erasebkgnd = 0x14;   
171 // //当系统颜色改变时,发送此消息给所有顶级窗口   
172 //const int wm_syscolorchange = 0x15;   
173 // //当系统进程发出wm_queryendsession消息后,此消息发送给应用程序,通知它对话是否结束   
174 //const int wm_endsession = 0x16;   
175 // //当隐藏或显示窗口是发送此消息给这个窗口   
176 //const int wm_showwindow = 0x18;   
177 // //发此消息给应用程序哪个窗口是激活的,哪个是非激活的   
178 //const int wm_activateapp = 0x1c;   
179 // //当系统的字体资源库变化时发送此消息给所有顶级窗口   
180 //const int wm_fontchange = 0x1d;   
181 // //当系统的时间变化时发送此消息给所有顶级窗口   
182 //const int wm_timechange = 0x1e;   
183 // //发送此消息来取消某种正在进行的摸态(操作)   
184 //const int wm_cancelmode = 0x1f;   
185 // //如果鼠标引起光标在某个窗口中移动且鼠标输入没有被捕获时,就发消息给某个窗口   
186 //const int wm_setcursor = 0x20;   
187 // //当光标在某个非激活的窗口中而用户正按着鼠标的某个键发送此消息给//当前窗口   
188 //const int wm_mouseactivate = 0x21;   
189 // //发送此消息给mdi子窗口//当用户点击此窗口的标题栏,或//当窗口被激活,移动,改变大小   
190 //const int wm_childactivate = 0x22;   
191 // //此消息由基于计算机的训练程序发送,通过wh_journalpalyback的hook程序分离出用户输入消息   
192 //const int wm_queuesync = 0x23;   
193 // //此消息发送给窗口当它将要改变大小或位置   
194 //const int wm_getminmaxinfo = 0x24;   
195 // //发送给最小化窗口当它图标将要被重画   
196 //const int wm_painticon = 0x26;   
197 // //此消息发送给某个最小化窗口,仅//当它在画图标前它的背景必须被重画   
198 //const int wm_iconerasebkgnd = 0x27;   
199 // //发送此消息给一个对话框程序去更改焦点位置   
200 //const int wm_nextdlgctl = 0x28;   
201 // //每当打印管理列队增加或减少一条作业时发出此消息    
202 //const int wm_spoolerstatus = 0x2a;   
203 // //当button,combobox,listbox,menu的可视外观改变时发送   
204 //const int wm_drawitem = 0x2b;   
205 // //当button, combo box, list box, list view control, or menu item 被创建时   
206 //const int wm_measureitem = 0x2c;   
207 // //此消息有一个lbs_wantkeyboardinput风格的发出给它的所有者来响应wm_keydown消息    
208 //const int wm_vkeytoitem = 0x2e;   
209 // //此消息由一个lbs_wantkeyboardinput风格的列表框发送给他的所有者来响应wm_char消息    
210 //const int wm_chartoitem = 0x2f;   
211 // //当绘制文本时程序发送此消息得到控件要用的颜色   
212 //const int wm_setfont = 0x30;   
213 // //应用程序发送此消息得到当前控件绘制文本的字体   
214 //const int wm_getfont = 0x31;   
215 // //应用程序发送此消息让一个窗口与一个热键相关连    
216 //const int wm_sethotkey = 0x32;   
217 // //应用程序发送此消息来判断热键与某个窗口是否有关联   
218 //const int wm_gethotkey = 0x33;   
219 // //此消息发送给最小化窗口,当此窗口将要被拖放而它的类中没有定义图标,应用程序能返回一个图标或光标的句柄,当用户拖放图标时系统显示这个图标或光标   
220 //const int wm_querydragicon = 0x37;   
221 // //发送此消息来判定combobox或listbox新增加的项的相对位置   
222 //const int wm_compareitem = 0x39;   
223 // //显示内存已经很少了   
224 //const int wm_compacting = 0x41;   
225 // //发送此消息给那个窗口的大小和位置将要被改变时,来调用setwindowpos函数或其它窗口管理函数   
226 //const int wm_windowposchanging = 0x46;   
227 // //发送此消息给那个窗口的大小和位置已经被改变时,来调用setwindowpos函数或其它窗口管理函数   
228 //const int wm_windowposchanged = 0x47;   
229 // //当系统将要进入暂停状态时发送此消息   
230 //const int wm_power = 0x48;   
231 // //当一个应用程序传递数据给另一个应用程序时发送此消息   
232 //const int wm_copydata = 0x4a;   
233 // //当某个用户取消程序日志激活状态,提交此消息给程序   
234 //const int wm_canceljourna = 0x4b;   
235 // //当某个控件的某个事件已经发生或这个控件需要得到一些信息时,发送此消息给它的父窗口    
236 //const int wm_notify = 0x4e;   
237 // //当用户选择某种输入语言,或输入语言的热键改变   
238 //const int wm_inputlangchangerequest = 0x50;   
239 // //当平台现场已经被改变后发送此消息给受影响的最顶级窗口   
240 //const int wm_inputlangchange = 0x51;   
241 // //当程序已经初始化windows帮助例程时发送此消息给应用程序   
242 //const int wm_tcard = 0x52;   
243 // //此消息显示用户按下了f1,如果某个菜单是激活的,就发送此消息个此窗口关联的菜单,否则就发送给有焦点的窗口,如果//当前都没有焦点,就把此消息发送给//当前激活的窗口   
244 //const int wm_help = 0x53;   
245 // //当用户已经登入或退出后发送此消息给所有的窗口,//当用户登入或退出时系统更新用户的具体设置信息,在用户更新设置时系统马上发送此消息   
246 //const int wm_userchanged = 0x54;   
247 // //公用控件,自定义控件和他们的父窗口通过此消息来判断控件是使用ansi还是unicode结构   
248 //const int wm_notifyformat = 0x55;   
249 // //当用户某个窗口中点击了一下右键就发送此消息给这个窗口   
250 // //const int wm_contextmenu = ??;   
251 // //当调用setwindowlong函数将要改变一个或多个 窗口的风格时发送此消息给那个窗口   
252 //const int wm_stylechanging = 0x7c;   
253 // //当调用setwindowlong函数一个或多个 窗口的风格后发送此消息给那个窗口   
254 //const int wm_stylechanged = 0x7d;   
255 // //当显示器的分辨率改变后发送此消息给所有的窗口   
256 //const int wm_displaychange = 0x7e;   
257 // //此消息发送给某个窗口来返回与某个窗口有关连的大图标或小图标的句柄   
258 //const int wm_geticon = 0x7f;   
259 // //程序发送此消息让一个新的大图标或小图标与某个窗口关联   
260 //const int wm_seticon = 0x80;   
261 // //当某个窗口第一次被创建时,此消息在wm_create消息发送前发送   
262 //const int wm_nccreate = 0x81;   
263 // //此消息通知某个窗口,非客户区正在销毁    
264 //const int wm_ncdestroy = 0x82;   
265 // //当某个窗口的客户区域必须被核算时发送此消息   
266 //const int wm_nccalcsize = 0x83;   
267 // //移动鼠标,按住或释放鼠标时发生   
268 //const int wm_nchittest = 0x84;   
269 // //程序发送此消息给某个窗口当它(窗口)的框架必须被绘制时   
270 //const int wm_ncpaint = 0x85;   
271 // //此消息发送给某个窗口仅当它的非客户区需要被改变来显示是激活还是非激活状态   
272 //const int wm_ncactivate = 0x86;   
273 // //发送此消息给某个与对话框程序关联的控件,widdows控制方位键和tab键使输入进入此控件通过应   
274 //const int wm_getdlgcode = 0x87;   
275 // //当光标在一个窗口的非客户区内移动时发送此消息给这个窗口 非客户区为:窗体的标题栏及窗 的边框体   
276 //const int wm_ncmousemove = 0xa0;   
277 // //当光标在一个窗口的非客户区同时按下鼠标左键时提交此消息   
278 //const int wm_nclbuttondown = 0xa1;   
279 // //当用户释放鼠标左键同时光标某个窗口在非客户区十发送此消息    
280 //const int wm_nclbuttonup = 0xa2;   
281 // //当用户双击鼠标左键同时光标某个窗口在非客户区十发送此消息   
282 //const int wm_nclbuttondblclk = 0xa3;   
283 // //当用户按下鼠标右键同时光标又在窗口的非客户区时发送此消息   
284 //const int wm_ncrbuttondown = 0xa4;   
285 // //当用户释放鼠标右键同时光标又在窗口的非客户区时发送此消息   
286 //const int wm_ncrbuttonup = 0xa5;   
287 // //当用户双击鼠标右键同时光标某个窗口在非客户区十发送此消息   
288 //const int wm_ncrbuttondblclk = 0xa6;   
289 // //当用户按下鼠标中键同时光标又在窗口的非客户区时发送此消息   
290 //const int wm_ncmbuttondown = 0xa7;   
291 // //当用户释放鼠标中键同时光标又在窗口的非客户区时发送此消息   
292 //const int wm_ncmbuttonup = 0xa8;   
293 // //当用户双击鼠标中键同时光标又在窗口的非客户区时发送此消息   
294 //const int wm_ncmbuttondblclk = 0xa9;   
295 // //wm_keydown 按下一个键   
296 //const int wm_keydown = 0x0100;   
297 // //释放一个键   
298 //const int wm_keyup = 0x0101;   
299 // //按下某键,并已发出wm_keydown, wm_keyup消息   
300 //const int wm_char = 0x102;   
301 // //当用translatemessage函数翻译wm_keyup消息时发送此消息给拥有焦点的窗口   
302 //const int wm_deadchar = 0x103;   
303 // //当用户按住alt键同时按下其它键时提交此消息给拥有焦点的窗口   
304 //const int wm_syskeydown = 0x104;   
305 // //当用户释放一个键同时alt 键还按着时提交此消息给拥有焦点的窗口   
306 //const int wm_syskeyup = 0x105;   
307 // //当wm_syskeydown消息被translatemessage函数翻译后提交此消息给拥有焦点的窗口   
308 //const int wm_syschar = 0x106;   
309 // //当wm_syskeydown消息被translatemessage函数翻译后发送此消息给拥有焦点的窗口   
310 //const int wm_sysdeadchar = 0x107;   
311 // //在一个对话框程序被显示前发送此消息给它,通常用此消息初始化控件和执行其它任务   
312 //const int wm_initdialog = 0x110;   
313 // //当用户选择一条菜单命令项或当某个控件发送一条消息给它的父窗口,一个快捷键被翻译   
314 //const int wm_command = 0x111;   
315 // //当用户选择窗口菜单的一条命令或//当用户选择最大化或最小化时那个窗口会收到此消息   
316 //const int wm_syscommand = 0x112;   
317 // //发生了定时器事件   
318 //const int wm_timer = 0x113;   
319 // //当一个窗口标准水平滚动条产生一个滚动事件时发送此消息给那个窗口,也发送给拥有它的控件   
320 //const int wm_hscroll = 0x114;   
321 // //当一个窗口标准垂直滚动条产生一个滚动事件时发送此消息给那个窗口也,发送给拥有它的控件   
322 //const int wm_vscroll = 0x115;   
323 // //当一个菜单将要被激活时发送此消息,它发生在用户菜单条中的某项或按下某个菜单键,它允许程序在显示前更改菜单   
324 //const int wm_initmenu = 0x116;   
325 // //当一个下拉菜单或子菜单将要被激活时发送此消息,它允许程序在它显示前更改菜单,而不要改变全部   
326 //const int wm_initmenupopup = 0x117;   
327 // //当用户选择一条菜单项时发送此消息给菜单的所有者(一般是窗口)   
328 //const int wm_menuselect = 0x11f;   
329 // //当菜单已被激活用户按下了某个键(不同于加速键),发送此消息给菜单的所有者   
330 //const int wm_menuchar = 0x120;   
331 // //当一个模态对话框或菜单进入空载状态时发送此消息给它的所有者,一个模态对话框或菜单进入空载状态就是在处理完一条或几条先前的消息后没有消息它的列队中等待   
332 //const int wm_enteridle = 0x121;   
333 // //在windows绘制消息框前发送此消息给消息框的所有者窗口,通过响应这条消息,所有者窗口可以通过使用给定的相关显示设备的句柄来设置消息框的文本和背景颜色   
334 //const int wm_ctlcolormsgbox = 0x132;   
335 // //当一个编辑型控件将要被绘制时发送此消息给它的父窗口通过响应这条消息,所有者窗口可以通过使用给定的相关显示设备的句柄来设置编辑框的文本和背景颜色   
336 //const int wm_ctlcoloredit = 0x133;   
337 
338 // //当一个列表框控件将要被绘制前发送此消息给它的父窗口通过响应这条消息,所有者窗口可以通过使用给定的相关显示设备的句柄来设置列表框的文本和背景颜色   
339 //const int wm_ctlcolorlistbox = 0x134;   
340 // //当一个按钮控件将要被绘制时发送此消息给它的父窗口通过响应这条消息,所有者窗口可以通过使用给定的相关显示设备的句柄来设置按纽的文本和背景颜色   
341 //const int wm_ctlcolorbtn = 0x135;   
342 // //当一个对话框控件将要被绘制前发送此消息给它的父窗口通过响应这条消息,所有者窗口可以通过使用给定的相关显示设备的句柄来设置对话框的文本背景颜色   
343 //const int wm_ctlcolordlg = 0x136;   
344 // //当一个滚动条控件将要被绘制时发送此消息给它的父窗口通过响应这条消息,所有者窗口可以通过使用给定的相关显示设备的句柄来设置滚动条的背景颜色   
345 //const int wm_ctlcolorscrollbar = 0x137;   
346 // //当一个静态控件将要被绘制时发送此消息给它的父窗口通过响应这条消息,所有者窗口可以 通过使用给定的相关显示设备的句柄来设置静态控件的文本和背景颜色   
347 //const int wm_ctlcolorstatic = 0x138;   
348 // //当鼠标轮子转动时发送此消息个当前有焦点的控件   
349 //const int wm_mousewheel = 0x20a;   
350 // //双击鼠标中键   
351 //const int wm_mbuttondblclk = 0x209;   
352 // //释放鼠标中键   
353 //const int wm_mbuttonup = 0x208;   
354 // //移动鼠标时发生,同wm_mousefirst   
355 // const int wm_mousemove = 0x200;   
356 // //按下鼠标左键   
357 //const int wm_lbuttondown = 0x201;   
358 // //释放鼠标左键   
359 //const int wm_lbuttonup = 0x202;   
360 // //双击鼠标左键   
361 //const int wm_lbuttondblclk = 0x203;   
362 // //按下鼠标右键   
363 //const int wm_rbuttondown = 0x204;   
364 // //释放鼠标右键   
365 //const int wm_rbuttonup = 0x205;   
366 // //双击鼠标右键   
367 //const int wm_rbuttondblclk = 0x206;   
368 // //按下鼠标中键   
369 //const int wm_mbuttondown = 0x207;   
370 
371 // const int wm_user = 0x0400;   
372 // const int mk_lbutton = 0x0001;   
373 // const int mk_rbutton = 0x0002;   
374 // const int mk_shift = 0x0004;   
375 // const int mk_control = 0x0008;   
376 // const int mk_mbutton = 0x0010;   
377 // const int mk_xbutton1 = 0x0020;   
378 // const int mk_xbutton2 = 0x0040;
379 #endregion
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.runtime.interopservices;
10 
11 namespace 消息传递_接_
12 {
13     public partial class form1 : form
14     {
15         public form1()
16         {
17             initializecomponent();
18         }
19 
20         class message
21         {
22             public const int user = 0x0400;
23             public const int wm_test = user + 101;
24             public const int wm_msg = user + 102;
25         }
26 
27         [dllimport("user32.dll", entrypoint = "sendmessage")]
28         private static extern int sendmessage(intptr hwnd, int msg, uint wparam, uint lparam);
29 
30         //响应和处理自定义消息
31         //在c#中,任何一个窗口都有也消息的接收处理函数,就是defproc函数 
32         protected override void defwndproc(ref system.windows.forms.message m)
33         {
34             string message;
35             switch (m.msg)
36             {
37                 case message.wm_test://处理消息
38 
39                     message = string.format("收到从应用程序发出的消息!参数为:{0}, {1}", m.wparam, m.lparam);
40                     messagebox.show(message);
41                     break;
42                 case message.wm_msg:
43 
44                     message = string.format("收到从dll发出的消息!参数为:{0}, {1}", m.wparam, m.lparam);
45 
46                     messagebox.show(message);//显示一个消息框 
47 
48                     break;
49 
50                 default:
51                     base.defwndproc(ref m);//调用基类函数处理非自定义消息
52                     break;
53             }
54         }
55         private void form1_keydown(object sender, keyeventargs e)
56         {
57             this.label1.text = e.keyvalue.tostring();
58         }
59     }
60 }

   2)、不同项目上的多进程通信

      

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.runtime.interopservices;
10 using datastruct;
11 
12 namespace sender
13 {
14     public partial class form1 : form
15     {
16         public form1()
17         {
18             initializecomponent();
19         }
20 
21         //win32 api函数
22         [dllimport("user32.dll", entrypoint = "sendmessage")]
23         private static extern int sendmessage(int hwnd, int msg, int wparam, ref datastruct lparam);
24 
25         [dllimport("user32.dll", entrypoint = "findwindow")]
26         private static extern int findwindow(string lpclassname, string lpwindowname);
27 
28         const int wm_copydata = 0x004a;
29 
30         private void btnsend_click(object sender, eventargs e)
31         {
32             int hwnd = findwindow(null, @"frmreceiver");//这是接收项目运行时的任务名
33             if (hwnd == 0)
34             {
35                 messagebox.show("未找到消息接受者!");
36             }
37             else
38             {
39                 byte[] sarr = system.text.encoding.default.getbytes(textbox2.text);
40                 int len = sarr.length;
41                 datastruct cds;
42                 cds.dwdata = (intptr)convert.toint16(textbox1.text);//可以是任意值
43                 cds.cbdata = len + 1;//指定lpdata内存区域的字节数
44                 cds.lpdata = textbox2.text;//发送给目标窗口所在进程的数据
45                 sendmessage(hwnd, wm_copydata, 0, ref cds);
46             }
47         }
48     }
49 }
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.runtime.interopservices;
10 using datastruct;
11 
12 namespace receiver
13 {
14     public partial class frmreceiver : form
15     {
16         const int wm_copydata = 0x004a;
17         public frmreceiver()
18         {
19             initializecomponent();
20         }
21 
22         protected override void defwndproc(ref message m)
23         {
24             switch (m.msg)
25             {
26                 case wm_copydata:
27                     datastruct cds = new datastruct();
28                     type t = cds.gettype();
29                     cds = (datastruct)m.getlparam(t);
30                     string strresult = cds.dwdata.tostring() + ":" + cds.lpdata;
31                     listview1.items.add(strresult);
32                     break;
33                 default:
34                     base.defwndproc(ref m);
35                     break;
36             }
37         }
38     }
39 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.runtime.interopservices;
 6 
 7 namespace datastruct
 8 {
 9     public struct datastruct
10     {
11         public intptr dwdata;
12         public int cbdata;
13         [marshalas(unmanagedtype.lpstr)]
14         public string lpdata;
15     }
16 }

 2.信号量

 1 using system;
 2 using system.threading;
 3 class program
 4 {
 5     static int g_cnt;
 6     static void main(string[] args)
 7     {
 8         semaphore semaphore = new semaphore(1, 1);
 9         parameterizedthreadstart ts = new parameterizedthreadstart(x =>
10         {
11             semaphore s = (semaphore)x;
12             for (int i = 0; i < 50000; ++i)
13             {
14                 s.waitone();
15                 ++g_cnt;
16                 s.release();
17             }
18         });
19         thread t1 = new thread(ts);
20         thread t2 = new thread(ts);
21         g_cnt = 0;
22         t1.start(semaphore);
23         t1.join();
24         console.writeline(g_cnt);
25         t2.start(semaphore);
26         t2.join();
27         console.writeline(g_cnt);
28         console.readkey();
29     }
30 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 
 7 #region 记住这个
 8 //semaphore信号量类(又称信号灯)
 9 //用于控制对资源池的访问。线程通过调用semaphore的waitone进入信号量,
10 //通过调用semaphore的release方法退出信号量。
11 
12 //信号量分为两种类型:局部信号量和已命名的系统信号量。如果您使用接受名称的构造函数创建
13 //semaphore 对象,则该对象与具有该名称的操作系统信号量关联。已命名的系统信号量在整个操作
14 //系统中都可见,可用于同步进程活动。您可以创建多个 semaphore 对象来表示同一个已命名的系
15 //统信号量,也可以使用 openexisting 方法打开现有的已命名系统信号量。www.it165.net
16 
17 //局部信号量仅存在于您的进程内。您的进程中任何引用局部 semaphore 对象的线程都可以使用它。
18 //每个 semaphore 对象都是一个单独的局部信号量。
19 #endregion
20 
21 namespace semaphore简单用法
22 {
23     class mysemaphore
24     {
25         //第一个参数,代表当前授权次数。
26         //      0表示没有授权(证)。
27         //第二个参数,代表semaphore实例最多能容纳几个授权证。
28         //      1表示最大授权次数为1次。
29         //      超出允许的授权次数,比如说sem.release连续调用了两次,会抛出异常。
30         public static semaphore sem = new semaphore(0, 1);
31         public static void main()
32         {
33             //添加一次授权。
34             //释放一个sem.waitone()的阻塞。
35             sem.release();
36             mythread mythrd1 = new mythread("thrd #1");
37             mythread mythrd2 = new mythread("thrd #2");
38             mythread mythrd3 = new mythread("thrd #3");
39             mythread mythrd4 = new mythread("thrd #4");
40             mythrd1.thrd.join();
41             mythrd2.thrd.join();
42             mythrd3.thrd.join();
43             mythrd4.thrd.join();
44 
45             console.readkey();
46         }
47     }
48     class mythread
49     {
50         public thread thrd;
51         public mythread(string name)
52         {
53             thrd = new thread(this.run);
54             thrd.name = name;
55             thrd.start();
56         }
57         void run()
58         {
59             console.writeline(thrd.name + "正在等待一个许可(证)……");
60             //如果不加参数会导致无限等待。
61             if (mysemaphore.sem.waitone(1000))
62             {
63                 console.writeline(thrd.name + "申请到许可(证)……");
64                 thread.sleep(500);
65                 //虽然下面添加了许可,但是,其它线程可能没拿到许可,超时退出了。
66                 console.writeline(thrd.name + "添加一个许可(证)……");
67                 mysemaphore.sem.release();
68             }
69             else
70             {
71                 console.writeline(thrd.name + " 超时(等了一段时间还是没拿到许可(证))退出……");
72             }
73         }
74     }
75 }

  信号量(共享内存)写                        信号量(共享内存)读

   

  1 using system.collections.generic;
  2 using system.componentmodel;
  3 using system.data;
  4 using system.drawing;
  5 using system.linq;
  6 using system.text;
  7 using system.windows.forms;
  8 using system.runtime.interopservices;
  9 using system.threading;
 10 using system;
 11 
 12 namespace _1
 13 {
 14     public partial class form1 : form
 15     {
 16         const int invalid_handle_value = -1;
 17         const int page_readwrite = 0x04;
 18         //共享内存
 19         [dllimport("kernel32.dll", entrypoint = "createfilemapping")]
 20         private static extern intptr createfilemapping(intptr hfile, //handle hfile,
 21          uint32 lpattributes,//lpsecurity_attributes lpattributes,  //0
 22          uint32 flprotect,//dword flprotect
 23          uint32 dwmaximumsizehigh,//dword dwmaximumsizehigh,
 24          uint32 dwmaximumsizelow,//dword dwmaximumsizelow,
 25          string lpname//lpctstr lpname
 26          );
 27 
 28         [dllimport("kernel32.dll", entrypoint = "openfilemapping")]
 29         private static extern intptr openfilemapping(
 30          uint32 dwdesiredaccess,//dword dwdesiredaccess,
 31          int binherithandle,//bool binherithandle,
 32          string lpname//lpctstr lpname
 33          );
 34 
 35         const int file_map_all_access = 0x0002;
 36         const int file_map_write = 0x0002;
 37 
 38         [dllimport("kernel32.dll", entrypoint = "mapviewoffile")]
 39         private static extern intptr mapviewoffile(
 40          intptr hfilemappingobject,//handle hfilemappingobject,
 41          uint32 dwdesiredaccess,//dword dwdesiredaccess
 42          uint32 dwfileoffsethight,//dword dwfileoffsethigh,
 43          uint32 dwfileoffsetlow,//dword dwfileoffsetlow,
 44          uint32 dwnumberofbytestomap//size_t dwnumberofbytestomap
 45          );
 46 
 47         [dllimport("kernel32.dll", entrypoint = "unmapviewoffile")]
 48         private static extern int unmapviewoffile(intptr lpbaseaddress);
 49 
 50         [dllimport("kernel32.dll", entrypoint = "closehandle")]
 51         private static extern int closehandle(intptr hobject);
 52 
 53 
 54 
 55         private semaphore m_write;  //可写的信号
 56         private semaphore m_read;  //可读的信号
 57         private intptr handle;     //文件句柄
 58         private intptr addr;       //共享内存地址
 59         uint maplength;            //共享内存长
 60 
 61         thread threadred;
 62         public form1()
 63         {
 64             initializecomponent();
 65             //threadred = new thread(new threadstart(init));
 66             //threadred.start();
 67             maplength = 1024;
 68         }
 69 
 70         private void button1_click(object sender, eventargs e)
 71         {
 72             try
 73             {
 74                 m_write = semaphore.openexisting("writemap");
 75                 m_read = semaphore.openexisting("readmap");
 76                 handle = openfilemapping(file_map_write, 0, "sharememory");//打开一个现成的文件映射对象的函数
 77                 addr = mapviewoffile(handle, file_map_all_access, 0, 0, 0);//将一个文件映射对象映射到当前应用程序的地址空间
 78                 //件映射对象映射到当前应用程序的地址空间后
 79                 m_write.waitone();
 80                 byte[] sendstr = encoding.default.getbytes(textbox1.text.tostring() + '\0');
 81                 //如果要是超长的话,应另外处理,最好是分配足够的内存
 82                 if (sendstr.length < maplength)
 83                     copy(sendstr, addr);
 84 
 85                 m_read.release();
 86                 m_write.release();
 87 
 88             }
 89             catch (waithandlecannotbeopenedexception)
 90             {
 91                 messagebox.show("不存在系统信号量!");
 92                 return;
 93             }
 94         }
 95 
 96         static unsafe void copy(byte[] bytesrc, intptr dst)
 97         {
 98             fixed (byte* psrc = bytesrc)
 99             {
100                 byte* pdst = (byte*)dst;
101                 byte* psrc = psrc;
102                 for (int i = 0; i < bytesrc.length; i++)
103                 {
104                     *pdst = *psrc;
105                     pdst++;
106                     psrc++;
107                 }
108             }
109         }
110     }
111 }
  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.runtime.interopservices;
 10 using system.threading;
 11 using system.diagnostics;
 12 
 13 
 14 namespace _3.信号量_共享内存_读
 15 {
 16     public partial class form1 : form
 17     {
 18         const int invalid_handle_value = -1;
 19         const int page_readwrite = 0x04;
 20 
 21         [dllimport("user32.dll")]
 22         private static extern bool showwindowasync(intptr hwnd, int cmdshow);
 23         [dllimport("user32.dll")]
 24         private static extern bool setforegroundwindow(intptr hwnd);
 25 
 26         //共享内存
 27         [dllimport("kernel32.dll", entrypoint = "createfilemapping")]
 28         private static extern intptr createfilemapping(intptr hfile, //handle hfile,
 29          uint32 lpattributes,//lpsecurity_attributes lpattributes,  //0
 30          uint32 flprotect,//dword flprotect
 31          uint32 dwmaximumsizehigh,//dword dwmaximumsizehigh,
 32          uint32 dwmaximumsizelow,//dword dwmaximumsizelow,
 33          string lpname//lpctstr lpname
 34          );
 35 
 36         [dllimport("kernel32.dll", entrypoint = "openfilemapping")]
 37         private static extern intptr openfilemapping(
 38          uint32 dwdesiredaccess,//dword dwdesiredaccess,
 39          int binherithandle,//bool binherithandle,
 40          string lpname//lpctstr lpname
 41          );
 42 
 43         const int file_map_all_access = 0x0002;
 44         const int file_map_write = 0x0002;
 45 
 46         [dllimport("kernel32.dll", entrypoint = "mapviewoffile")]
 47         private static extern intptr mapviewoffile(
 48          intptr hfilemappingobject,//handle hfilemappingobject,
 49          uint32 dwdesiredaccess,//dword dwdesiredaccess
 50          uint32 dwfileoffsethight,//dword dwfileoffsethigh,
 51          uint32 dwfileoffsetlow,//dword dwfileoffsetlow,
 52          uint32 dwnumberofbytestomap//size_t dwnumberofbytestomap
 53          );
 54 
 55         [dllimport("kernel32.dll", entrypoint = "unmapviewoffile")]
 56         private static extern int unmapviewoffile(intptr lpbaseaddress);
 57 
 58         [dllimport("kernel32.dll", entrypoint = "closehandle")]
 59         private static extern int closehandle(intptr hobject);
 60 
 61         private semaphore m_write;  //可写的信号
 62         private semaphore m_read;  //可读的信号
 63         private intptr handle;     //文件句柄
 64         private intptr addr;       //共享内存地址
 65         uint maplength;            //共享内存长
 66 
 67         //线程用来读取数据        
 68         thread threadred;
 69         public form1()
 70         {
 71             initializecomponent();
 72             init();
 73         }
 74 
 75         ///<summary>/// 初始化共享内存数据 创建一个共享内存
 76         private void init()
 77         {
 78             m_write = new semaphore(1, 1, "writemap");//开始的时候有一个可以写
 79             m_read = new semaphore(0, 1, "readmap");//没有数据可读
 80             maplength = 1024;
 81             intptr hfile = new intptr(invalid_handle_value);
 82             handle = createfilemapping(hfile, 0, page_readwrite, 0, maplength, "sharememory");
 83             addr = mapviewoffile(handle, file_map_all_access, 0, 0, 0);
 84 
 85             //handle = openfilemapping(0x0002, 0, "sharememory");
 86             //addr = mapviewoffile(handle, file_map_all_access, 0, 0, 0);
 87 
 88             threadred = new thread(new threadstart(threadreceive));
 89             threadred.isbackground = true;
 90             threadred.start();
 91         }
 92 
 93         /// <summary>
 94         /// 线程启动从共享内存中获取数据信息 
 95         /// </summary>
 96         private void threadreceive()
 97         {
 98             // delegate myi = new delegate(abc);
 99             while (true)
100             {
101                 try
102                 {
103                     //m_write = semaphore.openexisting("writemap");
104                     //m_read = semaphore.openexisting("readmap");
105                     //handle = openfilemapping(file_map_write, 0, "sharememory");
106 
107                     //读取共享内存中的数据:
108                     //是否有数据写过来
109                     m_read.waitone();
110                     //intptr m_sender = mapviewoffile(handle, file_map_all_access, 0, 0, 0);
111                     byte[] bytestr = new byte[100];
112                     bytecopy(bytestr, addr);
113                     string str = encoding.default.getstring(bytestr, 0, bytestr.length);
114 
115                     textbox1.text = str;
116                     // init();
117                     m_write = new semaphore(1, 1, "writemap");//开始的时候有一个可以写
118                     m_read = new semaphore(0, 1, "readmap");//没有数据可读
119                 }
120                 catch (waithandlecannotbeopenedexception)
121                 {
122                     continue;
123                     //thread.sleep(0);
124                 }
125 
126             }
127         }
128         public static void abc()
129         { }
130         //不安全的代码在项目生成的选项中选中允许不安全代码
131         static unsafe void bytecopy(byte[] dst, intptr src)
132         {
133             fixed (byte* pdst = dst)
134             {
135                 byte* pdst = pdst;
136                 byte* psrc = (byte*)src;
137                 while ((*pdst++ = *psrc++) != '\0') ;
138             }
139         }
140 
141         private void form1_load(object sender, eventargs e)
142         {
143             checkforillegalcrossthreadcalls = false;
144         }
145     }
146 }

 3.内存映射文件

1 ////持久内存映射文件
2 //持久文件是与磁盘上的源文件关联的内存映射文件。在最后一个进程使用完此文件后,数据将保存到磁盘上的源文件中。这些内存映射文件适合用来处理非常大的源文件。
3 ////非持久内存映射文件
4 //非持久文件是未与磁盘上的源文件关联的内存映射文件。当最后一个进程使用完此文件后,数据将丢失,并且垃圾回收功能将回收此文件。这些文件适用于为进程间通信 (ipc) 创建共享内存。
5 //createfromfile 方法基于磁盘上的现有文件创建一个内存映射文件

  1)、发送、接受(缺点最多5个整数)

    

把接收.exe放在发送运行文件的当前路径内。还有一点要记住,这只能发送数字,最多五个数字

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.runtime.interopservices;
10 using system.diagnostics;
11 
12 //目前,网上关于c#进程间通信的方法有很多种,但是总结起来它们不外乎从以下两个方面进行考虑
13 //一、在两个进程之间建立一个共同区域,其中一个进程改变这个区域的内容,而另一个进程则去读取它,
14 //反之亦然。比如,可以让两个进程共享同一块内存,通过改变和读取内存中的内容进行通信;或者,
15 //创建一个文件,两个进程同时占用,甚至可以利用注册表或者剪贴板充当这个“共同区域”。
16 //二、利用api函数去找到进程窗口的句柄,然后用api去控制这个窗口。例如,导入“user32.dll”中
17 //的findwindow、findwindowex函数查找窗口,并获取窗口句柄,也可直接利用c#中的process类来启动
18 //程序,并获取这个进程的主窗口的句柄,等等。
19 
20 //在编程时,我们往往需要选择一种即方便编写,效率又高的程序。第一种类型相对比较复杂,而且效率
21 //不高,相比来讲,第二种类型在不降低程序运行效率的情况下编写更简单。下面我就以一个示例程序来
22 //讲解如何使用process类和api实现两个进程之间的传输数据。
23 namespace _2发送
24 {
25     public partial class form1 : form
26     {
27         public form1()
28         {
29             initializecomponent();
30         }
31         public const int user = 0x0400;
32         public const int um_1 = user + 1;
33         [dllimport("user32.dll", entrypoint = "sendmessage")]
34         //此方法各个参数表示的意义
35         //wnd:接收消息的窗口的句柄。如果此参数为hwnd_broadcast,则消息将被发送到系统中所有顶层窗口,包括无效或不可见的非自身拥有的窗口、被覆盖的窗口和弹出式窗口,但消息不被发送到子窗口。
36         //msg:指定被发送的消息类型。
37         //wp:消息内容。
38         //lp:指定附加的消息指定信息。
39         private static extern int sendmessage(intptr wnd, int msg, intptr wp, intptr lp);
40 
41         processstartinfo info = new processstartinfo();
42         process pro = new process();
43 
44         private void form1_load(object sender, eventargs e)
45         {
46             info.filename = "2接受.exe";
47             pro.startinfo = info;
48         }
49 
50         private void button1_click(object sender, eventargs e)
51         {
52             pro.start();
53         }
54 
55         private void button2_click(object sender, eventargs e)
56         {
57             pro.kill();
58         }
59 
60         private void button3_click(object sender, eventargs e)
61         {
62             intptr hwnd = pro.mainwindowhandle;          //获取form1.exe主窗口句柄
63             int data = convert.toint32(this.textbox1.text);     //获取文本框数据            
64             sendmessage(hwnd, 0x0100, (intptr)data, (intptr)0); //发送wm_keydown消息            
65         }
66     }
67 }
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 
10 namespace _2接受
11 {
12     public partial class form1 : form
13     {
14         public form1()
15         {
16             initializecomponent();
17         }
18         //0x0100 ,即key down 事件
19         private void form1_keydown(object sender, keyeventargs e)
20         {
21             this.label1.text = convert.tostring(e.keyvalue);
22         }
23     }
24 }

  2)、一个项目中两个窗口模拟进程间通信

 

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.runtime.interopservices;
10 
11 //最主要的一部分:
12 ////发送消息
13 //public static extern void postmessage(intptr hwnd, int msg, int wparam, int lparam);
14 ////处理消息
15 //protected override void defwndproc(ref system.windows.forms.message m)
16 
17 //我们可以使用postmessage或sendmessage向目标窗口发送消息,
18 //并重载目标窗口的消息处理函数wndproc来响应消息。自定义消息的边界是0x0400,
19 //我们自定义的消息应当比它大。
20 
21 //为了传递字符串,我们需要把托管的string类型封送到非托管内存中,
22 //而在目标窗口从非托管内存中提取字符串,使用 marshal.stringtohglobalauto()
23 //和marshal.ptrtostringauto()即可。
24 namespace _2.一个项目中两个窗口模拟进程间通信
25 {
26     public partial class form1 : form
27     {
28         intptr h;
29         public form1()
30         {
31             initializecomponent();
32         }
33         private void button1_click(object sender, eventargs e)
34         {
35             var f = new form2();
36             h = f.handle;
37             f.show();
38         }
39         private void button2_click(object sender, eventargs e)
40         {
41             string str = textbox1.text;
42             intptr i = marshal.stringtohglobalauto(str);
43             win32api.postmessage(h, win32api.um_1, 0, i);
44         }
45     }
46 }
 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.runtime.interopservices;
10 
11 //在c#中,我们可以使用postmessage或sendmessage向目标窗口发送消息,
12 //并重载目标窗口的消息处理函数wndproc来响应消息。自定义消息的边界是0x0400,
13 //我们自定义的消息应当比它大。
14 
15 //为了传递字符串,我们需要把托管的string类型封送到非托管内存中,
16 //而在目标窗口从非托管内存中提取字符串,使用 marshal.stringtohglobalauto()
17 //和marshal.ptrtostringauto()即可。
18 namespace _2.一个项目中两个窗口模拟进程间通信
19 {
20     public partial class form2 : form
21     {
22         public form2()
23         {
24             initializecomponent();
25         }
26         //处理消息
27         protected override void wndproc(ref message m)
28         {
29             switch (m.msg)
30             {
31                 case win32api.um_1:
32                     string str = marshal.ptrtostringauto(m.lparam);
33                     textbox1.text += str + environment.newline;
34                     break;
35                 default:
36                     base.wndproc(ref m);
37                     break;
38             }
39         }
40     }
41 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.runtime.interopservices;
 6 //windows自定义消息wm_user和wm_app
 7 //常量是windows帮助应用程序定义私有窗口类里的私有消息,通常使用wm_user+一个整数值,但总值不能超过0x7fff。
 8 //#define wm_user       0x0400                  -->1024
 9 //常量是windows帮助应用程序定义私有消息,通常使用wm_app+一个整数值,但总值不能超过0xbfff。
10 //#define wm_app       0x8000                    -->32768
11 //这两个都定义在winuser.h中。
12 //范围
13 //表示
14 //0 ~ wm_user–1
15 namespace _2.一个项目中两个窗口模拟进程间通信
16 {
17     class win32api
18     {
19         #region msg
20         public const int user = 1;//0x0400;//用户自定义消息的开始数值1024
21         public const int um_1 = user + 1;
22         #endregion
23         #region api
24         [dllimport("user32.dll")]
25         //发送消息
26         public static extern void postmessage(intptr hwnd, int msg, int wparam, intptr lparam);
27         #endregion
28     }
29 }

   3)、内存映射(不操作文件)

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 //引用内存映射文件命名空间
 7 using system.io.memorymappedfiles;
 8 
 9 namespace _4.内存映射_写_
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             long capacity = 1 << 10 << 10;
16 
17             //创建或者打开共享内存
18             using (var mmf = memorymappedfile.createoropen("testmmf", capacity, memorymappedfileaccess.readwrite))
19             {
20                 //通过memorymappedfile的createviewaccssor方法获得共享内存的访问器
21                 var viewaccessor = mmf.createviewaccessor(0, capacity);
22                 //循环写入,使在这个进程中可以向共享内存中写入不同的字符串值
23                 while (true)
24                 {
25                     console.writeline("请输入一行要写入共享内存的文字:");
26 
27                     string input = console.readline();
28 
29                     //向共享内存开始位置写入字符串的长度
30                     viewaccessor.write(0, input.length);
31 
32                     //向共享内存4位置写入字符
33                     viewaccessor.writearray<char>(4, input.toarray(), 0, input.length);
34                 }
35             }
36         }
37     }
38 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading;
 6 //引用使用内存映射文件需要的命名空间
 7 using system.io.memorymappedfiles;
 8 
 9 namespace _4.内存映射_读1_
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             long capacity = 1 << 10 << 10;
16 
17             using (var mmf = memorymappedfile.openexisting("testmmf"))
18             {
19                 memorymappedviewaccessor viewaccessor = mmf.createviewaccessor(0, capacity);
20 
21                 //循环刷新共享内存字符串的值
22                 while (true)
23                 {
24                     //读取字符长度
25                     int strlength = viewaccessor.readint32(0);
26                     char[] charsinmmf = new char[strlength];
27                     //读取字符
28                     viewaccessor.readarray<char>(4, charsinmmf, 0, strlength);
29                     console.clear();
30                     console.write(charsinmmf);
31                     console.write("\r");
32                     thread.sleep(200);
33                 }
34             }
35         }
36     }
37 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io.memorymappedfiles;
 6 using system.io;
 7 
 8 namespace _4.内存映射_读2_
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             long capacity = 1 << 10 << 10;
15             //打开共享内存
16             using (var mmf = memorymappedfile.openexisting("testmmf"))
17             {
18                 //使用createviewstream方法返回stream实例
19                 using (var mmviewstream = mmf.createviewstream(0, capacity))
20                 {
21                     //这里要制定unicode编码否则会出问题
22                     using (binaryreader rdr = new binaryreader(mmviewstream, encoding.unicode))
23                     {
24                         while (true)
25                         {
26                             mmviewstream.seek(0, seekorigin.begin);
27 
28                             int length = rdr.readint32();
29 
30                             char[] chars = rdr.readchars(length);
31 
32                             console.write(chars);
33                             console.write("\r");
34 
35                             system.threading.thread.sleep(200);
36                             console.clear();
37                         }
38                     }
39                 }
40             }
41         }
42     }
43 }

   2)、文件存入内存(无映射)

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 
 7 //读取大文件可以使用它,但它不是最快的
 8 namespace _5.内存映射文件_读放读_
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             string content = string.empty;
15 
16             using (streamreader sr = new streamreader("1.txt"))
17             {
18                 content = sr.readtoend();//一次性读入内存
19             }
20             memorystream ms = new memorystream(encoding.getencoding("gb2312").getbytes(content));//放入内存流,以便逐行读取
21 
22             using (streamreader sr = new streamreader(ms))
23             {
24                 while (sr.peek() > -1)
25                 {
26                     console.writeline(sr.readline() + "\r\n");
27                 }
28             }
29             console.read();
30         }
31     }
32 }

   3)、内存映射文件、视图流(读)

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 using system.io.memorymappedfiles;
 7 
 8 namespace _5.内存映射文件_读放读_
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             var filepath = "1.txt";
15             var filesize = new fileinfo(filepath).length;
16 
17             using (var mm = memorymappedfile.createfromfile(filepath, filemode.open, null, 0, memorymappedfileaccess.read))
18             using (var stream = mm.createviewstream(0, filesize, memorymappedfileaccess.read))
19             using (var reader = new streamreader(stream, encoding.getencoding("gb2312")))
20             {
21                 console.writeline(reader.readtoend());
22             }
23             console.read();
24         }
25     }
26 }

  4)、内存映射文件、视图访问器(读)

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 using system.io.memorymappedfiles;
 7 
 8 namespace _5.内存映射文件_读放读_
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             var filepath = @"1.txt";
15             var filesize = new fileinfo(filepath).length;
16 
17             using (var mm = memorymappedfile.createfromfile(filepath, filemode.open, null, 0, memorymappedfileaccess.read))//已知文件 内容不要为空,要不会出错
18             using (var accessor = mm.createviewaccessor(0, filesize, memorymappedfileaccess.read))
19             {
20                 byte[] bytes = new byte[filesize];
21                 for (int i = 0; i < filesize; i++)
22                 {
23                     bytes[i] = accessor.readbyte(i);
24                 }
25 
26                 var results = encoding.getencoding("gb2312").getstring(bytes);
27                 console.writeline(results);
28             }
29             console.read();
30         }
31     }
32 }

   5)、内存映射文件内容、写入、读取(持久性)

    1.内存指定文件的内容映射在内存中(持久)

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io.memorymappedfiles;
 6 using system.io;
 7 using system.runtime.interopservices;
 8 //前提,这是把指定的文件内容加入到内存中
 9 namespace _2.内存映射指定文件_持久_向内存中写
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             //持久内存映射文件:基于现有文件创建一个具有指定公用名的内存映射文件
16             using (var mmf = memorymappedfile.createfromfile("1.txt", filemode.open, "myfile"))
17 
18             // using (var mmf = memorymappedfile.createfromfile("1.txt", filemode.open, "123",0, memorymappedfileaccess.readwrite))
19             {
20                 //通过指定的 偏移量和大小 创建内存映射文件视图服务器
21                 using (var accessor = mmf.createviewaccessor(0, 0, memorymappedfileaccess.readwrite)) //偏移量,可以控制数据存储的内存位置;大小,用来控制存储所占用的空间
22                 {
23                     console.read();
24                 }
25             }
26 
27         }
28     }
29 }

    2.内存映射指定文件内存中读(持久)

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io.memorymappedfiles;
 6 using system.runtime.interopservices;
 7 
 8 namespace _2.内存映射指定文件_持久_内存中读
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             //另一个进程或线程可以,在系统内存中打开一个具有指定名称的现有内存映射文件
15             using (var mmf = memorymappedfile.openexisting("myfile"))
16             {
17                 using (var accessor = mmf.createviewaccessor(0, 0, memorymappedfileaccess.readwrite))
18                 {
19                     long strlength = accessor.capacity; //访问器的容量
20                     int size = marshal.sizeof(typeof(char));
21 
22                     byte[] by = new byte[strlength];
23 
24                     for (long i = 0; i < strlength; i += size)
25                     {
26                         by[i] = accessor.readbyte(i);
27 
28                     } var results = encoding.getencoding("gb2312").getstring(by);
29                     console.writeline(results);
30                 }
31             }
32             console.read();
33         }
34     }
35 }

    3.向内存中写、内存映射物理文件内容更改(持久)

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io.memorymappedfiles;
 6 using system.io;
 7 using system.runtime.interopservices;
 8 //前提,这是把指定的文件内容加入到内存中
 9 namespace _2.内存映射指定文件_持久_向内存中写
10 {
11     class program
12     {
13         static void main(string[] args)
14         {
15             string filepath = "1.txt";
16             var filesize = new fileinfo(filepath).length;
17             int size = (int)filesize;
18 
19             console.writeline("请输入一行要写入共享内存的文字:");
20             string input = console.readline();
21 
22             //持久内存映射文件:基于现有文件创建一个具有指定公用名的内存映射文件
23             using (var mmf = memorymappedfile.createfromfile(filepath, filemode.open, "myfile"))
24             {
25                 //通过指定的 偏移量和大小 创建内存映射文件视图服务器
26                 using (var accessor = mmf.createviewaccessor(0, 0, memorymappedfileaccess.readwrite)) //偏移量,可以控制数据存储的内存位置;大小,用来控制存储所占用的空间
27                 {
28                     console.writeline(accessor.capacity);
29 
30                     //向共享内存开始位置写入字符串的长度
31                     accessor.write(0, input.length);
32 
33                     //向共享内存4位置写入字符                    
34                     accessor.writearray<char>(0, input.toarray(), 0, input.length);
35 
36                     console.read();
37                 }
38             }
39         }
40     }
41 }

  6)、非持久(内存映射)

 1 using system;
 2 using system.io;
 3 using system.io.memorymappedfiles;
 4 using system.runtime.interopservices;
 5 using system.threading;
 6 
 7 namespace 非持久_内存映射_
 8 {
 9     /// <summary>
10     /// 用于共享内存方式通信的 值类型 结构体
11     /// </summary>
12     public struct servicemsg
13     {
14         public int id;
15         public long nowtime;
16     }
17 
18     internal class program
19     {
20         private static void main(string[] args)
21         {
22             console.write("请输入共享内存公用名(默认:testmap):");
23             string sharename = console.readline();
24             if (string.isnullorempty(sharename))
25                 sharename = "testmap";
26             using (memorymappedfile mmf = memorymappedfile.createoropen(sharename, 1024000, memorymappedfileaccess.readwrite))
27             {
28                 mutex mutex = mutex.openexisting("testmapmutex");
29                 mutex.waitone();
30                 using (memorymappedviewstream stream = mmf.createviewstream(20, 0)) //注意这里的偏移量
31                 {
32                     var writer = new binarywriter(stream);
33                     for (int i = 5; i < 10; i++)
34                     {
35                         writer.write(i);
36                         console.writeline("{0}位置写入流:{0}", i);
37                     }
38                 }
39                 using (memorymappedviewaccessor accessor = mmf.createviewaccessor(1024, 10240))
40                 {
41                     int colorsize = marshal.sizeof(typeof(servicemsg));
42                     var color = new servicemsg();
43                     for (int i = 0; i < colorsize * 5; i += colorsize)
44                     {
45                         color.id = i;
46                         color.nowtime = datetime.now.ticks;
47                         //accessor.read(i, out color);
48                         accessor.write(i, ref color);
49                         console.writeline("{1}\tnowtime:{0}", new datetime(color.nowtime), color.id);
50                         thread.sleep(1000);
51                     }
52                 }
53                 thread.sleep(5000);
54 
55                 mutex.releasemutex();
56             }
57             console.writeline("测试: 我是 即时通讯 - 状态服务 我启动啦!!!");
58             console.readkey();
59         }
60     }
61 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system;
 6 using system.io;
 7 using system.io.memorymappedfiles;
 8 using system.runtime.interopservices;
 9 using system.threading;
10 
11 namespace _3.非持久_读写_
12 {
13     /// <summary>
14     /// 用于共享内存方式通信的 值类型 结构体
15     /// </summary>
16     public struct servicemsg
17     {
18         public int id;
19         public long nowtime;
20     }
21 
22     internal class program
23     {
24         private static void main(string[] args)
25         {
26             console.write("请输入共享内存公用名(默认:testmap):");
27             string sharename = console.readline();
28             if (string.isnullorempty(sharename))
29                 sharename = "testmap";
30             using (memorymappedfile mmf = memorymappedfile.createoropen(sharename, 1024000, memorymappedfileaccess.readwrite))
31             {
32                 bool mutexcreated;
33                 //进程间同步
34                 var mutex = new mutex(true, "testmapmutex", out mutexcreated);
35                 using (memorymappedviewstream stream = mmf.createviewstream()) //创建文件内存视图流
36                 {
37                     var writer = new binarywriter(stream);
38                     for (int i = 0; i < 5; i++)
39                     {
40                         writer.write(i);
41                         console.writeline("{0}位置写入流:{0}", i);
42                     }
43                 }
44 
45                 mutex.releasemutex();
46 
47                 console.writeline("启动状态服务,按【回车】读取共享内存数据");
48                 console.readline();
49 
50                 mutex.waitone();
51                 using (memorymappedviewstream stream = mmf.createviewstream())
52                 {
53                     var reader = new binaryreader(stream);
54                     for (int i = 0; i < 10; i++)
55                     {
56                         console.writeline("{1}位置:{0}", reader.readint32(), i);
57                     }
58                 }
59 
60                 using (memorymappedviewaccessor accessor = mmf.createviewaccessor(1024, 10240))
61                 {
62                     int colorsize = marshal.sizeof(typeof(servicemsg));
63                     servicemsg color;
64                     for (int i = 0; i < 50; i += colorsize)
65                     {
66                         accessor.read(i, out color);
67                         console.writeline("{1}\tnowtime:{0}", new datetime(color.nowtime), color.id);
68                     }
69                 }
70                 mutex.releasemutex();
71             }
72             console.writeline("测试: 我是 即时通讯 - 消息服务 我启动啦!!!");
73             console.readkey();
74         }
75     }
76 }

  7)、内存映射文件(电脑dll)

  1 using system;
  2 using system.collections.generic;
  3 using system.text;
  4 using system.runtime.interopservices;
  5 using system.io;
  6 using system.data.sqlclient;
  7 
  8 namespace _6.内存映射文件_dll_
  9 {
 10     class sharememory
 11     {
 12         [dllimport("kernel32.dll")]
 13         public static extern intptr createfilemapping(intptr hfile, intptr lpfilemappingattributes, uint flprotect, uint dwmaximumsizehigh,
 14             uint dwmaximumsizelow, string lpname);
 15 
 16         [dllimport("kernel32.dll")]
 17         public static extern intptr mapviewoffile(intptr hfilemappingobject, uint
 18             dwdesiredaccess, uint dwfileoffsethigh, uint dwfileoffsetlow, intptr dwnumberofbytestomap);
 19 
 20         [dllimport("kernel32.dll")]
 21         public static extern bool unmapviewoffile(intptr lpbaseaddress);
 22 
 23         [dllimport("kernel32.dll")]
 24         public static extern bool closehandle(intptr hobject);
 25 
 26         [dllimport("kernel32.dll")]
 27         public static extern intptr createfile(string lpfilename, int dwdesiredaccess, fileshare dwsharemode, intptr securityattrs,
 28             filemode dwcreationdisposition, int dwflagsandattributes, intptr htemplatefile);
 29 
 30         [dllimport("kernel32.dll")]
 31         public static extern uint getfilesize(intptr hfile, intptr lpfilesizehigh);
 32 
 33         public const int generic_read = -2147483648; //0x80000000
 34         public const int generic_write = 0x40000000;
 35         public const int generic_execute = 0x20000000;
 36         public const int generic_all = 0x10000000;
 37         public const int file_attribute_normal = 0x80;
 38         public const int file_flag_sequential_scan = 0x8000000;
 39         public const int invalid_handle_value = -1;
 40 
 41         public const int page_noaccess = 1;
 42         public const int page_readonly = 2;
 43         public const int page_readwrite = 4;
 44 
 45         public const int file_map_copy = 1;
 46         public const int file_map_write = 2;
 47         public const int file_map_read = 4;
 48 
 49         ////////////////////////////////////////
 50         public static string mappingfileread()
 51         {
 52             string result = "";
 53             try
 54             {
 55                 intptr vfilehandle = createfile("1.txt", generic_read | generic_write, fileshare.read | fileshare.write, intptr.zero, filemode.open,
 56                 file_attribute_normal | file_flag_sequential_scan, intptr.zero);
 57                 if (invalid_handle_value != (int)vfilehandle)
 58                 {
 59                     intptr vmappinghandle = createfilemapping(vfilehandle, intptr.zero, page_readwrite, 0, 0, "~mappingtemp");
 60                     if (vmappinghandle != intptr.zero)
 61                     {
 62                         intptr vhead = mapviewoffile(vmappinghandle, file_map_copy | file_map_read | file_map_write, 0, 0, intptr.zero);
 63                         if (vhead != intptr.zero)
 64                         {
 65                             uint vsize = getfilesize(vfilehandle, intptr.zero);
 66                             byte[] res = new byte[vsize];
 67                             marshal.copy(vhead, res, 0, (int)vsize);
 68                             result = asciiencoding.default.getstring(res);
 69                             string[] _str = result.split('|');
 70                             result = _str[0];
 71                             /*
 72                             //***************************************
 73                             //_intptr = marshal.readintptr(vhead);                             
 74                             byte[] contentbyte1 = new byte[vsize];
 75                             for (int i = 0; i < vsize; i++)
 76                             {
 77                                 byte vtemp = marshal.readbyte((intptr)((int)vhead + i));
 78                                 contentbyte1[i] = vtemp;                               
 79                             }
 80                             console.writeline(asciiencoding.default.getstring(contentbyte1));//全部值
 81                             //***************************************
 82                             byte[] contentbyte = new byte[vsize];
 83                             for (int i = 0; i < vsize; i++)
 84                             {
 85                                 byte vtemp = marshal.readbyte((intptr)((int)vhead + i));
 86                                 contentbyte[i] = vtemp;
 87                                 if (vtemp == '|')//设定标识结束符合
 88                                 {
 89                                     break;
 90                                 }
 91                             }                            
 92                             console.writeline(asciiencoding.default.getstring(contentbyte));//要取的值
 93                             result = asciiencoding.default.getstring(contentbyte);
 94                             //***************************************
 95                             */
 96                             unmapviewoffile(vhead);
 97                         }
 98                         closehandle(vmappinghandle);
 99                     }
100                     closehandle(vfilehandle);
101                 }
102 
103             }
104             catch
105             { }
106             return result;
107         }
108 
109         //////////////////////////////////
110         public static intptr invalidhandlevalue = new intptr(-1);
111         public static void mappingfilewrite(string val)
112         {
113             try
114             {
115                 intptr vfilehandle = createfile(@"c:/test.txt", generic_read | generic_write, fileshare.read | fileshare.write, intptr.zero, filemode.open,
116                 file_attribute_normal | file_flag_sequential_scan, intptr.zero);
117                 if (invalid_handle_value != (int)vfilehandle)
118                 {
119                     intptr vmappinghandle = createfilemapping(vfilehandle, intptr.zero, page_readwrite, 0, (uint32)(val.length + 1), "~mappingtemp");
120                     if (vmappinghandle != intptr.zero)
121                     {
122                         intptr vhead = mapviewoffile(vmappinghandle, file_map_copy | file_map_read | file_map_write, 0, 0, intptr.zero);
123                         if (vhead != intptr.zero)
124                         {
125                             byte[] by = asciiencoding.default.getbytes(val + "|"); //设定标识结束符合  |   
126                             marshal.copy(by, 0, vhead, by.length);
127                             unmapviewoffile(vhead);
128                         }
129                         closehandle(vmappinghandle);
130                     }
131                     closehandle(vfilehandle);
132                 }
133 
134             }
135             catch
136             { }
137         }
138 
139         //////////////////////////////////
140         public static void mappingwrite1(string val)
141         {
142             try
143             {
144                 intptr vmappinghandle = createfilemapping(invalidhandlevalue, intptr.zero, page_readwrite, 0, (uint32)(val.length + 1), "~mappingtemp");
145                 if (vmappinghandle != intptr.zero)
146                 {
147                     intptr vhead = mapviewoffile(vmappinghandle, file_map_copy | file_map_read | file_map_write, 0, 0, intptr.zero);
148                     if (vhead != intptr.zero)
149                     {
150                         byte[] by = asciiencoding.default.getbytes(val + "|"); //设定标识结束符合  |  
151                         marshal.copy(by, 0, vhead, by.length);
152                         unmapviewoffile(vhead);
153                     }
154                     //closehandle(vmappinghandle);
155                 }
156 
157             }
158             catch
159             { }
160         }
161 
162         //////////////////////////////////
163         public static string mappingread1()
164         {
165             string result = "";
166             try
167             {
168                 intptr vmappinghandle = createfilemapping(invalidhandlevalue, intptr.zero, page_readwrite, 0, 7, "~mappingtemp");
169                 if (vmappinghandle != intptr.zero)
170                 {
171                     intptr vhead = mapviewoffile(vmappinghandle, file_map_copy | file_map_read | file_map_write, 0, 0, intptr.zero);
172                     if (vhead != intptr.zero)
173                     {
174                         byte[] bytdata = new byte[7];
175                         marshal.copy(vhead, bytdata, 0, 7);
176                         result = asciiencoding.default.getstring(bytdata);
177                         unmapviewoffile(vhead);
178                         //console.writeline(result);自己填的
179                     }
180                     closehandle(vmappinghandle);
181                 }
182             }
183             catch
184             {
185             }
186             return result;
187         }
188         static void main(string[] args)
189         {
190             console.writeline(mappingfileread());
191             //mappingwrite1("123");
192             //mappingread1();
193             console.read();
194         }
195     }
196 }
197 
198 
199 #region
200 //namespace 
201 //{
202 //    public class 
203 //    {
204 //        [dllimport( "user32.dll", charset = charset.auto )]
205 //        public static extern intptr sendmessage( intptr hwnd, int msg, int wparam, intptr lparam );
206 
207 //        [dllimport( "kernel32.dll", charset = charset.auto )]
208 //        public static extern intptr createfilemapping( intptr hfile, intptr lpattributes, uint flprotect, uint dwmaxsizehi, uint dwmaxsizelow, string lpname );
209 
210 //        [dllimport( "kernel32.dll", charset = charset.auto )]
211 //        public static extern intptr openfilemapping( int dwdesiredaccess, [marshalas( unmanagedtype.bool )] bool binherithandle, string lpname );
212 
213 //        [dllimport( "kernel32.dll", charset = charset.auto )]
214 //        public static extern intptr mapviewoffile( intptr hfilemapping, uint dwdesiredaccess, uint dwfileoffsethigh, uint dwfileoffsetlow, uint dwnumberofbytestomap );
215 
216 //        [dllimport( "kernel32.dll", charset = charset.auto )]
217 //        public static extern bool unmapviewoffile( intptr pvbaseaddress );
218 
219 //        [dllimport( "kernel32.dll", charset = charset.auto )]
220 //        public static extern bool closehandle( intptr handle );
221 
222 //        [dllimport( "kernel32", entrypoint = "getlasterror" )]
223 //        public static extern int getlasterror();
224 
225 //        [dllimport( "kernel32.dll" )]
226 //        static extern void getsysteminfo( out system_info lpsysteminfo );
227 
228 //        [structlayout( layoutkind.sequential )]
229 //        public struct system_info
230 //        {
231 //            public ushort processorarchitecture;
232 //            ushort reserved;
233 //            public uint pagesize;
234 //            public intptr minimumapplicationaddress;
235 //            public intptr maximumapplicationaddress;
236 //            public intptr activeprocessormask;
237 //            public uint numberofprocessors;
238 //            public uint processortype;
239 //            public uint allocationgranularity;
240 //            public ushort processorlevel;
241 //            public ushort processorrevision;
242 //        }
243 //        /// <summary>
244 //        /// 获取系统的分配粒度
245 //        /// </summary>
246 //        /// <returns></returns>
247 //        public static uint getpartitionsize()
248 //        {
249 //            system_info sysinfo;
250 //            getsysteminfo( out sysinfo );
251 //            return sysinfo.allocationgranularity;
252 //        }
253 
254 //        const int error_already_exists = 183;
255 
256 //        const int file_map_copy = 0x0001;
257 //        const int file_map_write = 0x0002;
258 //        const int file_map_read = 0x0004;
259 //        const int file_map_all_access = 0x0002 | 0x0004;
260 
261 //        const int page_readonly = 0x02;
262 //        const int page_readwrite = 0x04;
263 //        const int page_writecopy = 0x08;
264 //        const int page_execute = 0x10;
265 //        const int page_execute_read = 0x20;
266 //        const int page_execute_readwrite = 0x40;
267 
268 //        const int sec_commit = 0x8000000;
269 //        const int sec_image = 0x1000000;
270 //        const int sec_nocache = 0x10000000;
271 //        const int sec_reserve = 0x4000000;
272 
273 //        intptr m_fhandle;
274 
275 //        intptr m_hsharedmemoryfile = intptr.zero;
276 //        intptr m_pwdata = intptr.zero;
277 //        bool m_balreadyexist = false;
278 //        bool m_binit = false;
279 //        uint m_memsize = 0x1400000;//20m
280 //        long m_offsetbegin = 0;
281 //        long m_filesize = 0;
282 //        filereader file = new filereader();
283 
284 
285 //        /// <summary>
286 //        ///  初始化文件
287 //        /// </summary>
288 //        /// <param name="memsize">缓冲大小</param>
289 //        public sharememory( string filename, uint memsize )
290 //        {
291 //            // 分页映射文件时,每页的起始位置startpos,必须为64k的整数倍。
292 //            // memsize即缓存区的大小必须是系统分配粒度的整倍说,window系统的分配粒度是64kb
293 //            this.m_memsize = memsize;
294 //            init( filename );
295 //        }
296 
297 
298 //        /// <summary>
299 //        /// 默认映射20m缓冲
300 //        /// </summary>
301 //        /// <param name="filename"></param>
302 //        public sharememory( string filename )
303 //        {
304 //            this.m_memsize = 0x1400000;
305 //            init( filename );
306 //        }
307 
308 //        ~sharememory()
309 //        {
310 //            close();
311 //        }
312 
313 //        /// <summary>
314 //        /// 初始化共享内存
315 //        /// 
316 //        /// 共享内存名称
317 //        /// 共享内存大小
318 //        /// </summary>
319 //        /// <param name="strname"></param>
320 //        protected void init( string strname )
321 //        {
322 //            //if (lngsize <= 0 || lngsize > 0x00800000) lngsize = 0x00800000;
323 
324 //            if ( !system.io.file.exists( strname ) ) throw new exception( "未找到文件" );
325 
326 //            system.io.fileinfo f = new system.io.fileinfo( strname );
327 
328 //            m_filesize = f.length;
329 
330 //            m_fhandle = file.open( strname );
331 
332 //            if ( strname.length > 0 )
333 //            {
334 //                //创建文件映射
335 //                m_hsharedmemoryfile = createfilemapping( m_fhandle, intptr.zero, ( uint )page_readonly, 0, ( uint )m_filesize, "mdata" );
336 //                if ( m_hsharedmemoryfile == intptr.zero )
337 //                {
338 //                    m_balreadyexist = false;
339 //                    m_binit = false;
340 //                    throw new exception( "createfilemapping失败lasterror=" + getlasterror().tostring() );
341 //                }
342 //                else
343 //                    m_binit = true;
344 
345 //                ////映射第一块文件
346 //                //m_pwdata = mapviewoffile(m_hsharedmemoryfile, file_map_read, 0, 0, (uint)m_memsize);
347 //                //if (m_pwdata == intptr.zero)
348 //                //{
349 //                //    m_binit = false;
350 //                //    throw new exception("m_hsharedmemoryfile失败lasterror=" + getlasterror().tostring());
351 //                //}
352 
353 //            }
354 //        }
355 //        /// <summary>
356 //        /// 获取高32位
357 //        /// </summary>
358 //        /// <param name="intvalue"></param>
359 //        /// <returns></returns>
360 //        private static uint gethighword( uint64 intvalue )
361 //        {
362 //            return convert.touint32( intvalue >> 32 );
363 //        }
364 //        /// <summary>
365 //        /// 获取低32位
366 //        /// </summary>
367 //        /// <param name="intvalue"></param>
368 //        /// <returns></returns>
369 //        private static uint getlowword( uint64 intvalue )
370 //        {
371 
372 //            return convert.touint32( intvalue & 0x00000000ffffffff );
373 //        }
374 
375 //        /// <summary>
376 //        /// 获取下一个文件块 块大小为20m
377 //        /// </summary>
378 //        /// <returns>false 表示已经是最后一块文件</returns>
379 //        public uint getnextblock()
380 //        {
381 //            if ( !this.m_binit ) throw new exception( "文件未初始化。" );
382 //            //if ( m_offsetbegin + m_memsize >= m_filesize ) return false;
383 
384 //            uint m_size = getmembersize();
385 //            if ( m_size == 0 ) return m_size;
386 
387 //            // 更改缓冲区大小
388 //            m_memsize = m_size;
389 
390 //            //卸载前一个文件
391 //            //bool l_result = unmapviewoffile( m_pwdata );
392 //            //m_pwdata = intptr.zero;
393 
394 
395 //            m_pwdata = mapviewoffile( m_hsharedmemoryfile, file_map_read, gethighword( ( uint64 )m_offsetbegin ), getlowword( ( uint64 )m_offsetbegin ), m_size );
396 //            if ( m_pwdata == intptr.zero )
397 //            {
398 //                m_binit = false;
399 //                throw new exception( "映射文件块失败" + getlasterror().tostring() );
400 //            }
401 //            m_offsetbegin = m_offsetbegin + m_size;
402 
403 //            return m_size; //创建成功
404 //        }
405 //        /// <summary>
406 //        /// 返回映射区大小
407 //        /// </summary>
408 //        /// <returns></returns>
409 //        private uint getmembersize()
410 //        {
411 //            if ( m_offsetbegin >= m_filesize )
412 //            {
413 //                return 0;
414 //            }
415 //            else if ( m_offsetbegin + m_memsize >= m_filesize )
416 //            {
417 //                long temp = m_filesize - m_offsetbegin;
418 //                return ( uint )temp;
419 //            }
420 //            else
421 //                return m_memsize;
422 //        }
423 
424 //        /// <summary>
425 //        /// 关闭内存映射
426 //        /// </summary>
427 //        public void close()
428 //        {
429 //            if ( m_binit )
430 //            {
431 //                unmapviewoffile( m_pwdata );
432 //                closehandle( m_hsharedmemoryfile );
433 //                file.close();
434 //            }
435 //        }
436 
437 //        /// <summary>
438 //        /// 从当前块中获取数据
439 //        /// </summary>
440 //        /// <param name="bytdata">数据</param>
441 //        /// <param name="lngaddr">起始数据</param>
442 //        /// <param name="lngsize">数据长度,最大值=缓冲长度</param>
443 //        /// <param name="unmap">读取完成是否卸载缓冲区</param>
444 //        /// <returns></returns>
445 //        public void read( ref byte[] bytdata, int lngaddr, int lngsize, bool unmap )
446 //        {
447 //            if ( lngaddr + lngsize > m_memsize )
448 //                throw new exception( "read操作超出数据区" );
449 //            if ( m_binit )
450 //            {
451 //                // string bb = marshal.ptrtostringauto(m_pwdata);//
452 //                marshal.copy( m_pwdata, bytdata, lngaddr, lngsize );
453 //            }
454 //            else
455 //            {
456 //                throw new exception( "文件未初始化" );
457 //            }
458 
459 //            if ( unmap )
460 //            {
461 //                bool l_result = unmapviewoffile( m_pwdata );
462 //                if ( l_result )
463 //                    m_pwdata = intptr.zero;
464 //            }
465 //        }
466 
467 //        /// <summary>
468 //        /// 从当前块中获取数据
469 //        /// </summary>
470 //        /// <param name="bytdata">数据</param>
471 //        /// <param name="lngaddr">起始数据</param>
472 //        /// <param name="lngsize">数据长度,最大值=缓冲长度</param>
473 //        /// <exception cref="exception: read操作超出数据区"></exception>
474 //        /// <exception cref="exception: 文件未初始化"></exception>
475 //        /// <returns></returns>
476 //        public void read( ref byte[] bytdata, int lngaddr, int lngsize )
477 //        {
478 //            if ( lngaddr + lngsize > m_memsize )
479 //                throw new exception( "read操作超出数据区" );
480 //            if ( m_binit )
481 //            {
482 //                marshal.copy( m_pwdata, bytdata, lngaddr, lngsize );
483 //            }
484 //            else
485 //            {
486 //                throw new exception( "文件未初始化" );
487 //            }
488 //        }
489 
490 //        /// <summary>
491 //        /// 从当前块中获取数据
492 //        /// </summary>
493 //        /// <param name="lngaddr">缓存区偏移量</param>
494 //        /// <param name="bytedata">数据数组</param>
495 //        /// <param name="startindex">数据数组开始复制的下标</param>
496 //        /// <param name="lngsize">数据长度,最大值=缓冲长度</param>
497 //        /// <exception cref="exception: 起始数据超过缓冲区长度"></exception>
498 //        /// <exception cref="exception: 文件未初始化"></exception>
499 //        /// <returns>返回实际读取值</returns>
500 //        public uint readbytes( int lngaddr, ref byte[] bytedata, int startindex, uint intsize )
501 //        {
502 //            if ( lngaddr >= m_memsize )
503 //                throw new exception( "起始数据超过缓冲区长度" );
504 
505 //            if ( lngaddr + intsize > m_memsize )
506 //                intsize = m_memsize - ( uint )lngaddr;
507 
508 //            if ( m_binit )
509 //            {
510 //                intptr s = new intptr( ( long )m_pwdata + lngaddr ); // 地址偏移
511 //                marshal.copy( s, bytedata, startindex, ( int )intsize );
512 //            }
513 //            else
514 //            {
515 //                throw new exception( "文件未初始化" );
516 //            }
517 
518 //            return intsize;
519 //        }
520 
521 //        /// <summary>
522 //        /// 写数据
523 //        /// </summary>
524 //        /// <param name="bytdata">数据</param>
525 //        /// <param name="lngaddr">起始地址</param>
526 //        /// <param name="lngsize">个数</param>
527 //        /// <returns></returns>
528 //        private int write( byte[] bytdata, int lngaddr, int lngsize )
529 //        {
530 //            if ( lngaddr + lngsize > m_memsize ) return 2; //超出数据区
531 //            if ( m_binit )
532 //            {
533 //                marshal.copy( bytdata, lngaddr, m_pwdata, lngsize );
534 //            }
535 //            else
536 //            {
537 //                return 1; //共享内存未初始化
538 //            }
539 //            return 0; //写成功
540 //        }
541 //    }
542 //    internal class filereader
543 //    {
544 //        const uint generic_read = 0x80000000;
545 //        const uint open_existing = 3;
546 //        system.intptr handle;
547 
548 //        [dllimport( "kernel32", setlasterror = true )]
549 //        public static extern system.intptr createfile(
550 //            string filename,          // file name
551 //            uint desiredaccess,       // access mode
552 //            uint sharemode,           // share mode
553 //            uint securityattributes,  // security attributes
554 //            uint creationdisposition, // how to create
555 //            uint flagsandattributes,  // file attributes
556 //            int htemplatefile         // handle to template file
557 //        );
558 
559 //        [system.runtime.interopservices.dllimport( "kernel32", setlasterror = true )]
560 //        static extern bool closehandle
561 //        (
562 //            system.intptr hobject // handle to object
563 //        );
564 
565 
566 
567 //        public intptr open( string filename )
568 //        {
569 //            // open the existing file for reading       
570 //            handle = createfile
571 //            (
572 //                filename,
573 //                generic_read,
574 //                0,
575 //                0,
576 //                open_existing,
577 //                0,
578 //                0
579 //            );
580 
581 //            if ( handle != system.intptr.zero )
582 //            {
583 //                return handle;
584 //            }
585 //            else
586 //            {
587 //                throw new exception( "打开文件失败" );
588 //            }
589 //        }
590 
591 //        public bool close()
592 //        {
593 //            return closehandle( handle );
594 //        }
595 //    }
596 //}
597 
598 
599 //using system;
600 //using system.collections.generic;
601 //using system.text;
602 //using system.runtime.interopservices;
603 //using system.io;
604 
605 //namespace testopenfilemap
606 //{
607 //    public class filemap
608 //    {
609 //        [structlayout(layoutkind.sequential)]
610 //        internal struct system_info
611 //        { 
612 //            public uint dwoemid; 
613 //            public uint dwpagesize; 
614 //            public uint lpminimumapplicationaddress; 
615 //            public uint lpmaximumapplicationaddress; 
616 //            public uint dwactiveprocessormask; 
617 //            public uint dwnumberofprocessors; 
618 //            public uint dwprocessortype; 
619 //            public uint dwallocationgranularity; 
620 //            public uint dwprocessorlevel; 
621 //            public uint dwprocessorrevision;    
622 //        } 
623 
624 //        private const uint generic_read = 0x80000000;
625 //        private const uint generic_write =0x40000000;
626 //        private const int open_existing = 3;
627 //        private const int invalid_handle_value = -1;
628 //        private const int file_attribute_normal = 0x80;
629 //        private const uint file_flag_sequential_scan = 0x08000000;
630 //        private const uint page_readwrite = 0x04;
631 
632 //        private const int file_map_copy = 1;
633 //        private const int file_map_write = 2;
634 //        private const int file_map_read = 4;
635 
636 //        /// <summary>
637 //        /// 内存映射文件句柄
638 //        /// </summary>
639 //        /// <param name="hfile"></param>
640 //        /// <param name="lpfilemappingattributes"></param>
641 //        /// <param name="flprotect"></param>
642 //        /// <param name="dwmaximumsizehigh"></param>
643 //        /// <param name="dwmaximumsizelow"></param>
644 //        /// <param name="lpname"></param>
645 //        /// <returns></returns>
646 //        [dllimport("kernel32.dll")]
647 //        internal static extern intptr createfilemapping(intptr hfile,
648 //            intptr lpfilemappingattributes, uint flprotect,
649 //            uint dwmaximumsizehigh,
650 //            uint dwmaximumsizelow, string lpname);
651 //        /// <summary>
652 //        /// 内存映射文件
653 //        /// </summary>
654 //        /// <param name="hfilemappingobject"></param>
655 //        /// <param name="dwdesiredaccess"></param>
656 //        /// <param name="dwfileoffsethigh"></param>
657 //        /// <param name="dwfileoffsetlow"></param>
658 //        /// <param name="dwnumberofbytestomap"></param>
659 //        /// <returns></returns>
660 //        [dllimport("kernel32.dll")]
661 //        internal static extern intptr mapviewoffile(intptr hfilemappingobject, uint
662 //            dwdesiredaccess, uint dwfileoffsethigh, uint dwfileoffsetlow,
663 //            uint dwnumberofbytestomap);
664 
665 //        /// <summary>
666 //        /// 撤消文件映像
667 //        /// </summary>
668 //        /// <param name="lpbaseaddress"></param>
669 //        /// <returns></returns>
670 //        [dllimport("kernel32.dll")]
671 //        internal static extern bool unmapviewoffile(intptr lpbaseaddress);
672 
673 //        /// <summary>
674 //        /// 关闭内核对象句柄
675 //        /// </summary>
676 //        /// <param name="hobject"></param>
677 //        /// <returns></returns>
678 //        [dllimport("kernel32.dll")]
679 //        internal static extern bool closehandle(intptr hobject);
680 
681 //        /// <summary>
682 //        /// 打开要映射的文件
683 //        /// </summary>
684 //        /// <param name="lpfilename"></param>
685 //        /// <param name="dwdesiredaccess"></param>
686 //        /// <param name="dwsharemode"></param>
687 //        /// <param name="securityattrs"></param>
688 //        /// <param name="dwcreationdisposition"></param>
689 //        /// <param name="dwflagsandattributes"></param>
690 //        /// <param name="htemplatefile"></param>
691 //        /// <returns></returns>
692 //        [dllimport("kernel32.dll")]
693 //        internal static extern intptr createfile(string lpfilename,
694 //            uint dwdesiredaccess, fileshare dwsharemode, intptr securityattrs,
695 //            filemode dwcreationdisposition, uint dwflagsandattributes, intptr htemplatefile);
696 //        /// <summary>
697 //        /// 得到文件大小
698 //        /// </summary>
699 //        /// <param name="hfile"></param>
700 //        /// <param name="highsize"></param>
701 //        /// <returns></returns>
702 //        [dllimport("kernel32.dll", setlasterror = true)]
703 //        internal static extern uint getfilesize(intptr hfile, out uint highsize);
704 
705 //        /// <summary>
706 //        /// 得到系统信息
707 //        /// </summary>
708 //        /// <param name="lpsysteminfo"></param>
709 //        [dllimport("kernel32.dll", setlasterror = true)]
710 //        internal static extern void getsysteminfo(ref system_info lpsysteminfo);
711 
712 //        /// <summary>
713 //        /// 使用内存文件映射得到文件内容
714 //        /// </summary>
715 //        /// <param name="path">文件路径</param>
716 //        /// <returns></returns>
717 //        public stringbuilder getfilecontent(string path)
718 //        {
719 //            stringbuilder sb = new stringbuilder();
720 //            intptr filehandle = createfile(path,
721 //        generic_read | generic_write, fileshare.read | fileshare.write,
722 //        intptr.zero, filemode.open,
723 //        file_attribute_normal | file_flag_sequential_scan, intptr.zero);
724 //            if (invalid_handle_value != (int)filehandle)
725 //            {
726 //                intptr mappingfilehandle = createfilemapping(
727 //                    filehandle, intptr.zero, page_readwrite, 0, 0, "~mappingtemp");
728 //                if (mappingfilehandle != intptr.zero)
729 //                {
730 //                    system_info systeminfo = new system_info(); ;
731 //                    getsysteminfo(ref systeminfo);
732 //                    //得到系统页分配粒度
733 //                    uint allocationgranularity = systeminfo.dwallocationgranularity;
734 //                    uint filesizehigh=0;
735 //                    //get file size
736 //                    uint filesize = getfilesize(filehandle, out filesizehigh);
737 //                    filesize |= (((uint)filesizehigh) << 32);
738 //                    //关闭文件句柄 
739 //                    closehandle(filehandle);
740 //                    uint fileoffset = 0;
741 //                    uint blockbytes = 1000 * allocationgranularity;
742 //                    if (filesize < 1000 * allocationgranularity)
743 //                        blockbytes = filesize;
744 //                    //分块读取内存,适用于几g的文件
745 //                    while (filesize > 0)
746 //                    {
747 //                        // 映射视图,得到地址 
748 //                        intptr lpbmapaddress = mapviewoffile(mappingfilehandle, file_map_copy | file_map_read | file_map_write,
749 //                           (uint)(fileoffset >> 32), (uint)(fileoffset & 0xffffffff),
750 //                           blockbytes);
751 //                        if (lpbmapaddress == intptr.zero)
752 //                        {
753 //                            return sb;
754 //                        }
755 //                        // 对映射的视图进行访问
756 //                        byte[] temp = new byte[blockbytes];
757 //                        //从非托管的内存中复制内容到托管的内存中
758 //                        marshal.copy(lpbmapaddress, temp, 0, (int)blockbytes);
759 
760 //                        //用循环太慢了,文件有几m的时候就慢的要死,还是用上面的方法直接
761 //                        //for (uint i = 0; i < dwblockbytes; i++)
762 //                        //{
763 //                        //    byte vtemp = marshal.readbyte((intptr)((int)lpbmapaddress + i));
764 //                        //    temp[i] = vtemp;
765 //                        //}
766 
767 //                        //此时用ascii解码比较快,但有中文会有乱码,用gb2312即ansi编码也比较快,16m的文件大概4秒就读出来了
768 //                        //但用unicode解码,文件大的时候会非常慢,会现卡死的状态,不知道为什么?
769 //                        //asciiencoding encoding = new asciiencoding();
770 //                        //system.text.unicodeencoding encoding = new unicodeencoding();
771 //                        //sb.append(encoding.getstring(temp));
772 //                        sb.append(system.text.encoding.getencoding("gb2312").getstring(temp));
773 //                        // 撤消文件映像
774 //                        unmapviewoffile(lpbmapaddress);
775 //                        // 修正参数
776 //                        fileoffset += blockbytes;
777 //                        filesize -= blockbytes;
778 //                    }
779 
780 //                    //close file mapping handle
781 //                    closehandle(mappingfilehandle);
782 //                }
783 //            }
784 //            return sb;
785 //        }
786 
787 //    }
788 //}
789 #endregion

  8)、内存映射文件(共享内存)     

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.text;
 7 using system.windows.forms;
 8 
 9 namespace 内存映射文件_共享内存_
10 {
11     public partial class form1 : form
12     {
13         public form1()
14         {
15             initializecomponent();
16         }
17 
18         sharemem memdb = new sharemem();
19 
20         private void btnopen_click(object sender, eventargs e)
21         {
22             if (memdb.init("yfmemtest", 10240) != 0)
23             {
24                 //初始化失败
25                 messagebox.show("初始化失败");
26             }
27             else
28             {
29                 btnopen.enabled = false;
30                 chkwrite.enabled = true;
31                 tmrtime.enabled = true;
32             }
33         }
34 
35         private void tmrtime_tick(object sender, eventargs e)
36         {
37             byte[] bytdata = new byte[16];
38             int intret = memdb.read(ref bytdata, 0, 16);
39             lstdata.items.clear();
40             if (intret == 0)
41             {
42                 for (int i = 0; i < 16; i++)
43                 {
44                     lstdata.items.add(bytdata[i].tostring());
45                 }
46 
47                 if (chkwrite.checked)
48                 {
49                     bytdata[0]++;
50                     bytdata[1] += 2;
51                     if (bytdata[0] > 200) bytdata[0] = 0;
52                     if (bytdata[1] > 200) bytdata[1] = 0;
53                     memdb.write(bytdata, 0, 16);
54                 }
55             }
56         }
57     }
58 }

练习:

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.io;
 6 using system.io.memorymappedfiles;
 7 using system.threading;
 8 //createnew 和 createoropen 方法创建一个未映射到磁盘上的现有文件的内存映射文件
 9 namespace 练习1非持久文件内存映射
10 {
11     class program
12     {
13         // process a:
14         static void main(string[] args)
15         {
16             using (memorymappedfile mmf = memorymappedfile.createnew("字符串的知识.txt", 10000))
17             {
18                 bool mutexcreated;
19                 mutex mutex = new mutex(true, "testmapmutex", out mutexcreated);
20                 using (memorymappedviewstream stream = mmf.createviewstream())
21                 {
22                     binarywriter writer = new binarywriter(stream);
23                     writer.write(1);
24                 }
25                 mutex.releasemutex();
26 
27                 console.writeline("start process b and press enter to continue.");
28                 console.readline();
29 
30                 console.writeline("start process c and press enter to continue.");
31                 console.readline();
32 
33                 mutex.waitone();
34                 using (memorymappedviewstream stream = mmf.createviewstream())
35                 {
36                     binaryreader reader = new binaryreader(stream);
37                     console.writeline("process a says: {0}", reader.readboolean());
38                     console.writeline("process b says: {0}", reader.readboolean());
39                     console.writeline("process c says: {0}", reader.readboolean());
40                 }
41                 mutex.releasemutex();
42             }
43             console.readkey();
44         }
45     }
46 }
  1 using system;
  2 using system.io;
  3 using system.io.memorymappedfiles;
  4 using system.text;
  5 
  6 namespace consoledemo
  7 {
  8     class program
  9     {
 10         private const string txt_file_path = @"a.txt";
 11         private const string split_varchar = "囧";
 12         private const char split_char = '囧';
 13         private static long file_size = 0;
 14         static void main(string[] args)
 15         {
 16             //long ttargetrownum = 39999999;
 17             long ttargetrownum = 10000000;
 18             datetime begintime = datetime.now;
 19             string line = creatememorymapfile(ttargetrownum);
 20             double totalseconds = datetime.now.subtract(begintime).totalseconds;
 21             console.writeline(line);
 22             console.writeline(string.format("查找第{0}行,共耗时:{1}s", ttargetrownum, totalseconds));
 23             console.readline();
 24         }
 25 
 26         /// <summary>
 27         /// 创建内存映射文件
 28         /// </summary>
 29         private static string creatememorymapfile(long ttargetrownum)
 30         {
 31             string line = string.empty;
 32             using (filestream fs = new filestream(txt_file_path, filemode.open, fileaccess.readwrite))
 33             {
 34                 long targetrownum = ttargetrownum + 1;//目标行
 35                 long currownum = 1;//当前行
 36                 file_size = fs.length;
 37                 using (memorymappedfile mmf = memorymappedfile.createfromfile(fs, "test", fs.length, memorymappedfileaccess.readwrite, null, handleinheritability.none, false))
 38                 {
 39                     long offset = 0;
 40                     //int limit = 250;
 41                     int limit = 200;
 42                     try
 43                     {
 44                         stringbuilder sbdefinerowline = new stringbuilder();
 45                         do
 46                         {
 47                             long remaining = fs.length - offset;
 48                             using (memorymappedviewstream mmstream = mmf.createviewstream(offset, remaining > limit ? limit : remaining))
 49                             //using (memorymappedviewstream mmstream = mmf.createviewstream(offset, remaining))
 50                             {
 51                                 offset += limit;
 52                                 using (streamreader sr = new streamreader(mmstream))
 53                                 {
 54                                     //string ss = sr.readtoend().tostring().replace("\n", "囧").replace(environment.newline, "囧");
 55                                     string ss = sr.readtoend().tostring().replace("\n", split_varchar).replace(environment.newline, split_varchar);
 56                                     if (currownum <= targetrownum)
 57                                     {
 58                                         if (currownum < targetrownum)
 59                                         {
 60                                             string s = sbdefinerowline.tostring();
 61                                             int pos = s.lastindexof(split_char);
 62                                             if (pos > 0)
 63                                                 sbdefinerowline.remove(0, pos);
 64 
 65                                         }
 66                                         else
 67                                         {
 68                                             line = sbdefinerowline.tostring();
 69                                             return line;
 70                                         }
 71                                         if (ss.contains(split_varchar))
 72                                         {
 73                                             currownum += getnewlinenumsofstr(ss);
 74                                             sbdefinerowline.append(ss);
 75                                         }
 76                                         else
 77                                         {
 78                                             sbdefinerowline.append(ss);
 79                                         }
 80                                     }
 81                                     //sbdefinerowline.append(ss);
 82                                     //line = sbdefinerowline.tostring();
 83                                     //if (ss.contains(environment.newline))
 84                                     //{
 85                                     //    ++currownum;
 86                                     //    //currownum++;
 87                                     //    //currownum += getnewlinenumsofstr(ss);
 88                                     //    //sbdefinerowline.append(ss);
 89                                     //}
 90                                     //if (currownum == targetrownum)
 91                                     //{
 92                                     //    string s = "";
 93                                     //}
 94 
 95                                     sr.dispose();
 96                                 }
 97 
 98                                 mmstream.dispose();
 99                             }
100                         } while (offset < fs.length);
101                     }
102                     catch (exception e)
103                     {
104                         console.writeline(e.message);
105                     }
106                     return line;
107                 }
108             }
109         }
110 
111         private static long getnewlinenumsofstr(string s)
112         {
113             string[] _lst = s.split(split_char);
114             return _lst.length - 1;
115         }
116     }
117 }

 有个进程+映射综合程序自己写!!!!!

 

 四、网络编程

了解部分:

1.tup

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.net;
 6 using system.net.sockets;
 7 
 8 namespace _2.s
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             byte[] sendbuf = encoding.utf8.getbytes("hello!");    //发给客户端的消息;
15             byte[] recvbuf = new byte[1024];      //申请接收缓存;  
16             int recvbytes = 0;                 //接收字节数;  
17             string recvmsg = null;            //接收消息;  
18 
19             ipendpoint localep = new ipendpoint(ipaddress.parse("172.16.2.93"), 6666);        //本地端地址  
20             tcplistener listener = new tcplistener(localep);            //建立监听类,并绑定到指定的端地址  
21             listener.start(10);           //开始监听                                                              
22             console.writeline("服务器开始监听—等待客户连接....");
23             tcpclient remoteclient = listener.accepttcpclient();  //等待连接(阻塞)  
24             console.writeline("用户:{0}  已连接!", remoteclient.client.remoteendpoint.tostring());     //打印客户端连接信息;  
25             remoteclient.client.send(sendbuf);     //发送欢迎信息; 
26 
27             try
28             {
29                 while (true)
30                 {
31                     recvbytes = remoteclient.client.receive(recvbuf);           //接受服务器发送过来的消息;  
32                     recvmsg = encoding.utf8.getstring(recvbuf, 0, recvbytes);   //将接受到的字节码转化为string类型;  
33                     console.writeline("用户:  {0}.", recvmsg);             //打印我是毕小帅;
34 
35                     //string str = console.readline();
36                     //byte[] sendf = encoding.utf8.getbytes(str);
37                     //remoteclient.client.send(sendf);
38                 }
39             }
40             catch
41             {
42                 remoteclient.close();                  //关闭连接;  
43                 console.read();
44             }
45         }
46     }
47 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.net;
 6 using system.net.sockets;
 7 
 8 namespace _1.c
 9 {
10     class program
11     {
12         static void main(string[] args)
13         {
14             byte[] sendbuf = encoding.utf8.getbytes("我是毕小帅");    //发给服务端的消息;
15             byte[] recvbuf = new byte[1024];      //申请接收缓存;  
16             int recvbytes = 0;                 //接收字节数;  
17             string recvmsg = null;            //接收消息;  
18             //127.0.0.1
19             ipendpoint remoteep = new ipendpoint(ipaddress.parse("172.16.2.93"), 6666);//远程服务器端地址;  
20             tcpclient remoteserver = new tcpclient();//创建tcpclient类来与服务器通信;  
21             remoteserver.connect(remoteep);          //调用connect方法连接远端服务器;  
22             console.writeline("我的ip地址: {0}.", remoteserver.client.localendpoint);//打印自己使用的端地址;  
23             recvbytes = remoteserver.client.receive(recvbuf);           //接受服务器发送过来的消息;  
24             recvmsg = encoding.utf8.getstring(recvbuf, 0, recvbytes);   //将接受到的字节码转化为string类型;  
25             console.writeline("服务器:  {0}.", recvmsg);             //打印欢迎信息; 
26 
27             remoteserver.client.send(sendbuf);                          //发给服务端的消息
28 
29             while (true)
30             {
31                 //recvbytes = remoteserver.client.receive(recvbuf);           
32                 //recvmsg = encoding.utf8.getstring(recvbuf, 0, recvbytes);   
33                 //console.writeline("用户:  {0}.", recvmsg); 
34 
35                 string str = console.readline();
36                 byte[] sendf = encoding.utf8.getbytes(str);
37                 remoteserver.client.send(sendf);
38             }
39             console.read();
40         }
41     }
42 }

2.udp
注意:udp没有服务端这个概念,我只是模拟形容个服务端

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 using system.net.sockets;
 7 using system.net;
 8 using system.threading;
 9 namespace udp_server
10 {
11     class program
12     {
13         static socket server;
14         static void main(string[] args)
15         {
16             server = new socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp);//定义udp
17             server.bind(new ipendpoint(ipaddress.parse("172.16.2.93"), 6001));//绑定端口号和ip
18             console.writeline("服务端已经开启");
19             thread t = new thread(recivemsg);//开启接收消息线程
20             t.start();
21 
22             thread t2 = new thread(sendmsg);//开启发送消息线程
23             t2.start();
24         }
25         /// <summary>
26         /// 向特定ip的主机的端口发送数据报
27         /// </summary>
28         static void sendmsg()
29         {
30             endpoint point = new ipendpoint(ipaddress.parse("172.16.2.93"), 6000);
31             while (true)
32             {
33                 string msg = console.readline();
34                 server.sendto(encoding.utf8.getbytes(msg), point);
35             }
36         }
37         /// <summary>
38         /// 接收发送给本机ip对应端口号的数据报
39         /// </summary>
40         static void recivemsg()
41         {
42             while (true)
43             {
44                 endpoint point = new ipendpoint(ipaddress.any, 0);//用来保存发送方的ip和端口号
45                 byte[] buffer = new byte[1024];
46                 int length = server.receivefrom(buffer, ref point);//接收数据报
47                 string message = encoding.utf8.getstring(buffer, 0, length);
48                 console.writeline(point.tostring() + message);
49             }
50         }
51     }
52 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 using system.net;
 7 using system.net.sockets;
 8 using system.threading;
 9 namespace udp_client
10 {
11     class program
12     {
13         static socket client;
14         static void main(string[] args)
15         {
16             client = new socket(addressfamily.internetwork, sockettype.dgram, protocoltype.udp);
17             client.bind(new ipendpoint(ipaddress.parse("172.16.2.93"), 6000));
18             thread t = new thread(sendmsg);
19             t.start();
20             thread t2 = new thread(recivemsg);
21             t2.start();
22             console.writeline("客户端已经开启");
23         }
24         /// <summary>
25         /// 向特定ip的主机的端口发送数据报
26         /// </summary>
27         static void sendmsg()
28         {
29             endpoint point = new ipendpoint(ipaddress.parse("172.16.2.93"), 6001);
30             while (true)
31             {
32                 string msg = console.readline();
33                 client.sendto(encoding.utf8.getbytes(msg), point);
34             }
35         }
36 
37         /// <summary>
38         /// 接收发送给本机ip对应端口号的数据报
39         /// </summary>
40         static void recivemsg()
41         {
42             while (true)
43             {
44                 endpoint point = new ipendpoint(ipaddress.any, 0);//用来保存发送方的ip和端口号
45                 byte[] buffer = new byte[1024];
46                 int length = client.receivefrom(buffer, ref point);//接收数据报
47                 string message = encoding.utf8.getstring(buffer, 0, length);
48                 console.writeline(point.tostring() + message);
49             }
50         }
51     }
52 }

3.标准的socket

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.net;
 6 using system.net.sockets;
 7 
 8 //服务器端:
 9 //第一步:用指定的端口号和服务器的ip建立一个endpoint对像;
10 //第二步:建立一个socket对像;
11 //第三步:用socket对像的bind()方法绑定endpoint;
12 //第四步:用socket对像的listen()方法开始监听;
13 //第五步:接受到客户端的连接,用socket对像的accept()方法创建新的socket对像用于和请求的客户端进行通信;
14 //第六步:通信结束后一定记得关闭socket;
15 namespace 标准的socket_server_
16 {
17     class program
18     {
19         static void main(string[] args)
20         {
21             int port = 2000;
22             string host = "127.0.0.1";
23 
24             ///创建终结点(endpoint)
25             ipaddress ip = ipaddress.parse(host);//把ip地址字符串转换为ipaddress类型的实例
26             ipendpoint ipe = new ipendpoint(ip, port);//用指定的端口和ip初始化ipendpoint类的新实例
27 
28             ///创建socket并开始监听
29             socket s = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);//创建一个socket对像,如果用udp协议,则要用sockettype.dgram类型的套接字
30             s.bind(ipe);//绑定endpoint对像(2000端口和ip地址)
31             s.listen(0);//开始监听
32             console.writeline("等待客户端连接");
33 
34             ///接受到client连接,为此连接建立新的socket,并接受信息
35             socket temp = s.accept();//为新建连接创建新的socket
36             console.writeline("建立连接");
37             string recvstr = "";
38             byte[] recvbytes = new byte[1024];
39             int bytes;
40             bytes = temp.receive(recvbytes, recvbytes.length, 0);//从客户端接受信息
41             recvstr += encoding.ascii.getstring(recvbytes, 0, bytes);
42 
43             ///给client端返回信息
44             console.writeline("server get message:{0}", recvstr);//把客户端传来的信息显示出来
45             string sendstr = "ok!client send message successful!";
46             byte[] bs = encoding.ascii.getbytes(sendstr);
47             temp.send(bs, bs.length, 0);//返回信息给客户端
48             temp.close();
49             s.close();
50             console.readline();
51         }
52     }
53 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.net;
 6 using system.net.sockets;
 7 
 8 //第一步:用指定的端口号和服务器的ip建立一个endpoint对像;
 9 //第二步:建立一个socket对像;
10 //第三步:用socket对像的connect()方法以上面建立的endpoint对像做为参数,向服务器发出连接请求;
11 //第四步:如果连接成功,就用socket对像的send()方法向服务器发送信息;
12 //第五步:用socket对像的receive()方法接受服务器发来的信息 ;
13 //第六步:通信结束后一定记得关闭socket;
14 namespace 标准socket_client_
15 {
16     class program
17     {
18         static void main(string[] args)
19         {
20             try
21             {
22                 int port = 2000;
23                 string host = "127.0.0.1";
24                 ///创建终结点endpoint
25                 ipaddress ip = ipaddress.parse(host);
26                 //ipaddress ipp = new ipaddress("127.0.0.1");
27                 ipendpoint ipe = new ipendpoint(ip, port);//把ip和端口转化为ipendpoint实例
28 
29                 ///创建socket并连接到服务器
30                 socket c = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);//创建socket
31                 console.writeline("conneting…");
32                 c.connect(ipe);//连接到服务器
33 
34                 ///向服务器发送信息
35                 string sendstr = "hello!this is a socket test";
36                 byte[] bs = encoding.ascii.getbytes(sendstr);//把字符串编码为字节
37                 console.writeline("send message");
38                 c.send(bs, bs.length, 0);//发送信息
39 
40                 ///接受从服务器返回的信息
41                 string recvstr = "";
42                 byte[] recvbytes = new byte[1024];
43                 int bytes;
44                 bytes = c.receive(recvbytes, recvbytes.length, 0);//从服务器端接受返回信息
45                 recvstr += encoding.ascii.getstring(recvbytes, 0, bytes);
46                 console.writeline("client get message:{0}", recvstr);//显示服务器返回信息
47                 ///一定记着用完socket后要关闭
48                 c.close();
49             }
50             catch (argumentnullexception e)
51             {
52                 console.writeline("argumentnullexception: {0}", e);
53             }
54             catch (socketexception e)
55             {
56                 console.writeline("socketexception:{0}", e);
57             }
58             console.writeline("press enter to exit");
59             console.readkey();
60         }
61     }
62 }

 

详细讲解:

1.复习委托机制

   

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.threading;
10 
11 namespace _1.委托机制
12 {
13     public partial class form1 : form
14     {
15         //第一步:
16         //定义委托
17         delegate void chengekjdelegate(int value);
18         //声明委托
19         chengekjdelegate chengekjdelegate;
20 
21         public form1()
22         {
23             initializecomponent();
24         }
25 
26         private void butstart_click(object sender, eventargs e)
27         {
28             //第四步:
29             //实例委托
30             chengekjdelegate = new chengekjdelegate(setprogressbarvalue1);
31             setprogressbarvalue(chengekjdelegate);
32 
33             //这里不用担心实例化两次会不会产生什么错误,主线程是按顺序从上到下执行
34             //没有开启新的线程,所以这里执行的线程只有主线程,第一个实例结束后才能开始第二个
35             chengekjdelegate = new chengekjdelegate(setprogessbarvalue2);
36             setprogressbarvalue(chengekjdelegate);
37         }
38 
39         //第五步:
40         //创建一个调用这个委托的方法
41         private void setprogressbarvalue(chengekjdelegate setvalue)
42         {
43             for (int i = 0; i <= 100; i++)
44             {
45                 application.doevents();//实验时可以用它,做项目时看需求再说,这是阻塞直线程的
46                 thread.sleep(50);
47                 //这时把setvalue看成setprogessbar1(参数)方法
48                 setvalue(i);
49             }
50         }
51 
52         //这是第二步:
53         //要进行委托的方法,设置进度条1的方法
54         private void setprogressbarvalue1(int value)
55         {
56             progressbar1.value = value;
57         }
58         //设置进度条2的方法
59         private void setprogessbarvalue2(int value)
60         {
61             progressbar2.value = value;
62         }
63     }
64 }

细心一些会发现:点击开始之后,拖动窗体进度条会停止不动。进度条在滚动时突然关闭程序会发现程序还在运行没有立即停止。

2.复习回调机制

跟第一图是一样的

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.threading;
10 
11 //回调=线程+委托
12 namespace _2.回调机制
13 {
14     public partial class form1 : form
15     {
16         //定义回调
17         private delegate void setprogressbarvalueht(int value);
18         //声明回调
19         private setprogressbarvalueht setprogressbarvalueht;
20 
21         public form1()
22         {
23             initializecomponent();
24         }
25 
26         private void butstart_click(object sender, eventargs e)
27         {
28             //checkforillegalcrossthreadcalls = false;//虽然它是比较万能的跨线程操作,不建议用它,建议回调
29             //用委托替代上面的这个跨线程
30             setprogressbarvalueht = new setprogressbarvalueht(setvaluewt);
31             thread setvaluethread = new thread(setprogressbar2);
32             setvaluethread.isbackground = true;
33             setvaluethread.start();
34 
35             for (int i = 0; i <= 100; i++)
36             {
37                 application.doevents();
38                 progressbar1.value = i;
39                 thread.sleep(50);
40             }
41         }
42 
43         //设置进度条2线程的方法
44         private void setprogressbar2()
45         {
46             for (int i = 0; i <= 100; i++)
47             {
48                 //progressbar2.value = i;//当用委托回调时这行也要改了
49                 progressbar2.invoke(setprogressbarvalueht, i);
50                 thread.sleep(50);
51             }
52         }
53 
54         //设置进度条2的 被委托的方法
55         private void setvaluewt(int value)
56         {
57             progressbar2.value = value;
58         }
59     }
60 }

点击开始之后,拖动进度条,明显发现不同

3.tcp服务端

  1 using system;
  2 using system.net;
  3 using system.net.sockets;
  4 using system.text;
  5 using system.data;
  6 using system.drawing;
  7 using system.windows.forms;
  8 using system.threading;
  9 using system.collections.generic;
 10 using system.componentmodel;
 11 
 12 namespace tcp服务端
 13 {
 14     public partial class frmmain : form
 15     {
 16         // 显示接收消息回调
 17         private delegate void showreceivemsgcallback(string text);
 18         private showreceivemsgcallback showreceivemsgcallback;
 19 
 20         // 网络连接相关
 21         private tcplistener mytcplistener;  // tcp连接侦听器
 22         private networkstream ns;                 // 网络数据流
 23         private tcpclient tcpclient;              // tcp客户端
 24         private thread tcpclientacceptthread;   // 客户端连接监听线程
 25 
 26         // 窗体构造方法
 27         public frmmain()
 28         {
 29             initializecomponent();
 30         }
 31 
 32         // 窗体启动加载事件
 33         private void frmmain_load(object sender, eventargs e)
 34         {
 35             // 初始化回调
 36             showreceivemsgcallback = new showreceivemsgcallback(showreceivemsg);
 37         }
 38 
 39         // 开始监听按钮被单击事件
 40         private void btnstartlisten_click(object sender, eventargs e)
 41         {
 42             try
 43             {
 44                 // 创建并实例化ip终端结点
 45                 ipendpoint ipendpoint =
 46                     new ipendpoint(ipaddress.parse(txtserverip.text), convert.toint32(txtserverport.text));
 47                 // 实例化tcp连接侦听器
 48                 mytcplistener = new tcplistener(ipendpoint);
 49                 // 启动tcp连接侦听器
 50                 mytcplistener.start();
 51                 // 创建并启动tcp连接侦听接受线程
 52                 tcpclientacceptthread = new thread(tcpclientaccept);
 53                 tcpclientacceptthread.isbackground = true;
 54                 tcpclientacceptthread.start();
 55                 // 修改控件状态
 56                 btnstartlisten.enabled = false;
 57                 btnstoplisten.enabled = true;
 58             }
 59             catch (exception ex)
 60             {
 61                 messagebox.show(ex.message);
 62             }
 63         }
 64 
 65         // 停止监听按钮被单击事件
 66         private void btnstoplisten_click(object sender, eventargs e)
 67         {
 68             // 停止监听
 69             mytcplistener.stop();
 70             // 终止监听线程
 71             tcpclientacceptthread.abort();
 72             // 修改控件状态
 73             btnstartlisten.enabled = true;
 74             btnstoplisten.enabled = false;
 75         }
 76 
 77         // tcp连接侦听接受线程
 78         private void tcpclientaccept()
 79         {
 80             try
 81             {
 82                 // 接收tcp客户端
 83                 tcpclient = mytcplistener.accepttcpclient();
 84                 // 获取绑定的网络数据流
 85                 ns = tcpclient.getstream();
 86 
 87                 // 循环接收消息
 88                 while (true)
 89                 {
 90                     int readlen = tcpclient.available;
 91                     if (readlen > 0)
 92                     {
 93                         // 创建并实例化用于存放数据的字节数组
 94                         byte[] getdata = new byte[readlen];
 95                         // 从网络数据流中读取数据
 96                         ns.read(getdata, 0, getdata.length);
 97                         // 将字节数组转换为文本形式
 98                         string getmsg = encoding.default.getstring(getdata);
 99                         // 将消息添加到接收消息列表中
100                         lstreceivemsg.invoke(showreceivemsgcallback, getmsg);
101                         thread.sleep(5000);
102                         // 返回相同消息给客户端
103                         ns.write(getdata, 0, getdata.length);
104                     }
105                 }
106             }
107             catch (threadabortexception)
108             {
109                 // 人为终止线程
110             }
111             catch (exception ex)
112             {
113                 // 连接发生异常
114                 messagebox.show(ex.message);
115                 // 释放相关系统资源
116                 if (tcpclient != null)
117                     tcpclient.close();
118                 if (ns != null)
119                     ns.dispose();
120             }
121         }
122 
123         // 显示接收消息回调方法
124         private void showreceivemsg(string text)
125         {
126             lstreceivemsg.items.add(text);
127         }
128     }
129 }

4.同步tcp客户端

  1 using system;
  2 using system.net;
  3 using system.net.sockets;
  4 using system.text;
  5 using system.data;
  6 using system.drawing;
  7 using system.windows.forms;
  8 using system.threading;
  9 using system.collections.generic;
 10 using system.componentmodel;
 11 
 12 namespace 同步tcp客户端
 13 {
 14     public partial class frmmain : form
 15     {
 16         // 显示接收消息回调
 17         private delegate void showreceivemsgcallback(string msg);
 18         private showreceivemsgcallback showreceivemsgcallback;
 19         // 修改进度条值回调
 20         private delegate void setprogressbarvaluecallback();
 21         private setprogressbarvaluecallback setprogressbarvaluecallback;
 22 
 23         // * 网络连接相关 *
 24         private tcpclient mytcpclient;             // tcp客户端
 25         private networkstream ns;                 // 网络数据流
 26         private thread receivemsgthread;      // 接收消息线程
 27 
 28 
 29         // 窗体构造方法
 30         public frmmain()
 31         {
 32             initializecomponent();
 33         }
 34 
 35         // 窗体启动加载事件
 36         private void frmmain_load(object sender, eventargs e)
 37         {
 38             // 初始化回调
 39             showreceivemsgcallback = new showreceivemsgcallback(showreceivemsg);
 40             setprogressbarvaluecallback = new setprogressbarvaluecallback(setprogressbarvalue);
 41         }
 42 
 43         // 发起连接按钮被单击事件
 44         private void btnconnect_click(object sender, eventargs e)
 45         {
 46             // 创建并实例化ip终端结点
 47             ipendpoint ipendpoint =
 48                 new ipendpoint(ipaddress.parse(txtserverip.text), convert.toint32(txtserverport.text));
 49             // 实例化tcp客户端
 50             mytcpclient = new tcpclient();
 51 
 52             try
 53             {
 54                 // 发起tcp连接
 55                 mytcpclient.connect(ipendpoint);
 56                 // 获取绑定的网络数据流
 57                 ns = mytcpclient.getstream();
 58                 // 实例化并启动接收消息线程
 59                 receivemsgthread = new thread(receivemsg);
 60                 receivemsgthread.start();
 61                 // 修改控件状态
 62                 btnconnect.enabled = false;
 63                 btndisconnect.enabled = true;
 64                 btnsendmsg.enabled = true;
 65             }
 66             catch (exception ex)
 67             {
 68                 // 捕捉到连接异常
 69                 messagebox.show(ex.message);
 70             }
 71         }
 72 
 73         // 断开连接按钮被单击事件
 74         private void btndisconnect_click(object sender, eventargs e)
 75         {
 76             // 断开tcp连接
 77             mytcpclient.close();
 78             // 销毁绑定的网络数据流
 79             ns.dispose();
 80             // 销毁接收消息线程
 81             receivemsgthread.abort();
 82             // 修改控件状态
 83             btnconnect.enabled = true;
 84             btndisconnect.enabled = false;
 85             btnsendmsg.enabled = false;
 86         }
 87 
 88         // 发送消息按钮被单击事件
 89         private void btnsendmsg_click(object sender, eventargs e)
 90         {
 91             // 将要发送的文本转换为字符数组形式
 92             byte[] senddata = encoding.default.getbytes(txtsendmsg.text);
 93             // 将数据写入到网络数据流中
 94             ns.write(senddata, 0, senddata.length);
 95         }
 96 
 97         // 接收消息线程
 98         private void receivemsg()
 99         {
100             while (true)
101             {
102                 try
103                 {
104                     // 创建并实例化用于存放数据的字节数组
105                     byte[] getdata = new byte[1024];
106                     // 从网络数据流中读取数据
107                     ns.read(getdata, 0, getdata.length);
108                     // 将字节数组转换为文本形式
109                     string getmsg = encoding.default.getstring(getdata);
110                     // 将消息添加到接收消息列表中
111                     lstreceivemsg.invoke(showreceivemsgcallback, getmsg);
112                     // 修改进度条值
113                     pgprogressbar.invoke(setprogressbarvaluecallback);
114                 }
115                 catch (threadabortexception)
116                 {
117                     // 捕捉到线程被终止异常则表示人为的断开tcp连接
118                     // 不需要弹出错误提示
119                 }
120                 catch (exception ex)
121                 {
122                     // 接收消息发生异常
123                     messagebox.show(ex.message);
124                     // 释放相关系统资源
125                     if (ns != null)
126                         ns.dispose();
127                     break;
128                 }
129             }
130         }
131 
132         // 显示接收消息方法
133         private void showreceivemsg(string msg)
134         {
135             lstreceivemsg.items.add(msg);
136         }
137 
138         // 修改进度条值的方法
139         private void setprogressbarvalue()
140         {
141             // 判断是否已经到进度条最大值
142             if (pgprogressbar.value < pgprogressbar.maximum)
143             {
144                 // 未到最大值,递增1
145                 pgprogressbar.value++;
146             }
147             else
148             {
149                 // 已到最大值,回到起点0
150                 pgprogressbar.value = 0;
151             }
152         }
153     }
154 }

5.异步tcp客户端

  1 using system;
  2 using system.net;
  3 using system.net.sockets;
  4 using system.text;
  5 using system.data;
  6 using system.drawing;
  7 using system.windows.forms;
  8 using system.threading;
  9 using system.collections.generic;
 10 using system.componentmodel;
 11 
 12 namespace 异步tcp客户端
 13 {
 14     public partial class frmmain : form
 15     {
 16         // 显示接收消息回调
 17         private delegate void showreceivemsgcallback(string msg);
 18         private showreceivemsgcallback showreceivemsgcallback;
 19         // 修改进度条值回调
 20         private delegate void setprogressbarvaluecallback();
 21         private setprogressbarvaluecallback setprogressbarvaluecallback;
 22         // 接收消息回调
 23         private delegate void receivemsgcallback(out string msg);
 24         private receivemsgcallback receivemsgcallback;
 25 
 26         // * 网络连接相关 *
 27         private tcpclient mytcpclient;             // tcp客户端
 28         private networkstream ns;                 // 网络数据流
 29         private thread receivemsgthread;      // 接收消息线程
 30 
 31         // 窗体构造方法
 32         public frmmain()
 33         {
 34             initializecomponent();
 35         }
 36 
 37         // 窗体启动加载事件
 38         private void frmmain_load(object sender, eventargs e)
 39         {
 40             // 初始化回调
 41             showreceivemsgcallback = new showreceivemsgcallback(showreceivemsg);
 42             setprogressbarvaluecallback = new setprogressbarvaluecallback(setprogressbarvalue);
 43             receivemsgcallback = new receivemsgcallback(receivemsgmethod);
 44         }
 45 
 46         // 发起连接按钮被单击事件
 47         private void btnconnect_click(object sender, eventargs e)
 48         {
 49             // 创建连接异步回调
 50             asynccallback connectcallback = new asynccallback(connectmethod);
 51             // 实例化tcp客户端
 52             mytcpclient = new tcpclient();
 53             // 发起tcp异步连接
 54             iasyncresult result = mytcpclient.beginconnect(
 55                 ipaddress.parse(txtserverip.text), convert.toint32(txtserverport.text), connectcallback, mytcpclient);
 56             messagebox.show("异步发起连接!");
 57         }
 58 
 59         // 断开连接按钮被单击事件
 60         private void btndisconnect_click(object sender, eventargs e)
 61         {
 62             // 销毁接收消息线程
 63             receivemsgthread.abort();
 64         }
 65 
 66         // 发送消息按钮被单击事件
 67         private void btnsendmsg_click(object sender, eventargs e)
 68         {
 69             // 将要发送的文本转换为字符数组形式
 70             byte[] senddata = encoding.default.getbytes(txtsendmsg.text);
 71             // 将数据写入到网络数据流中
 72             ns.write(senddata, 0, senddata.length);
 73         }
 74 
 75         // 接收消息线程
 76         private void receivemsg()
 77         {
 78             while (true)
 79             {
 80                 try
 81                 {
 82                     string getmsg = null;
 83                     // 开始异步接收消息
 84                     iasyncresult result = receivemsgcallback.begininvoke(out getmsg, null, null);
 85                     // 循环滚动进度条
 86                     while (!result.iscompleted)
 87                     {
 88                         pgprogressbar.invoke(setprogressbarvaluecallback);
 89                         application.doevents();
 90                         thread.sleep(500);
 91                     }
 92                     // 结束异步接收消息
 93                     receivemsgcallback.endinvoke(out getmsg, result);
 94 
 95                     if (getmsg != null)
 96                     {
 97                         // 将消息添加到接收消息列表中
 98                         lstreceivemsg.invoke(showreceivemsgcallback, getmsg);
 99                     }
100                 }
101                 catch (threadabortexception)
102                 {
103                     // 捕捉到线程被终止异常则表示人为的断开tcp连接
104                     // 不需要弹出错误提示
105                 }
106                 catch (exception ex)
107                 {
108                     // 接收消息发生异常
109                     messagebox.show(ex.message);
110                     // 释放相关系统资源
111                     if (ns != null)
112                         ns.dispose();
113                     break;
114                 }
115             }
116         }
117 
118         // 连接异步回调
119         private void connectmethod(iasyncresult iar)
120         {
121             try
122             {
123                 // 获取对象
124                 mytcpclient = (tcpclient)iar.asyncstate;
125                 // 结束异步连接
126                 mytcpclient.endconnect(iar);
127                 // 获取绑定的网络数据流
128                 ns = mytcpclient.getstream();
129                 // 实例化并启动接收消息线程
130                 receivemsgthread = new thread(receivemsg);
131                 receivemsgthread.start();
132             }
133             catch (exception ex)
134             {
135                 // 捕捉到连接异常
136                 messagebox.show(ex.message);
137             }
138         }
139 
140         // 接收消息异步回调
141         private void receivemsgmethod(out string msg)
142         {
143             msg = null;
144             try
145             {
146                 // 创建并实例化用于存放数据的字节数组
147                 byte[] getdata = new byte[1024];
148                 // 从网络数据流中读取数据
149                 ns.read(getdata, 0, getdata.length);
150                 // 将字节数组转换为文本形式
151                 msg = encoding.default.getstring(getdata);
152             }
153             catch (exception ex)
154             {
155                 // 接收消息发生异常
156                 messagebox.show(ex.message);
157                 // 释放相关系统资源
158                 if (ns != null)
159                     ns.dispose();
160             }
161         }
162 
163         // 显示接收消息方法
164         private void showreceivemsg(string msg)
165         {
166             lstreceivemsg.items.add(msg);
167         }
168 
169         // 修改进度条值的方法
170         private void setprogressbarvalue()
171         {
172             // 判断是否已经到进度条最大值
173             if (pgprogressbar.value < pgprogressbar.maximum)
174             {
175                 // 未到最大值,递增1
176                 pgprogressbar.value++;
177             }
178             else
179             {
180                 // 已到最大值,回到起点0
181                 pgprogressbar.value = 0;
182             }
183         }
184     }
185 }

6.udp进程通信

    

  1 using system;
  2 using system.net;
  3 using system.net.sockets;
  4 using system.text;
  5 using system.data;
  6 using system.drawing;
  7 using system.windows.forms;
  8 using system.threading;
  9 using system.collections.generic;
 10 using system.componentmodel;
 11 
 12 namespace upd进程通信
 13 {
 14     public partial class frmmain : form
 15     {
 16         // 显示消息回调
 17         private delegate void showmsgcallback(string text);
 18         private showmsgcallback showmsgcallback;
 19 
 20         private udpclient myudpclient;  // udp客户端
 21         private udpclient anonyudpclient;   // 匿名udp客户端
 22 
 23         // 窗构造方法
 24         public frmmain()
 25         {
 26             initializecomponent();
 27         }
 28 
 29         // 窗体启动加载事件
 30         private void frmmain_load(object sender, eventargs e)
 31         {
 32             // 初始化回调
 33             showmsgcallback = new showmsgcallback(showmsg);
 34         }
 35 
 36         // 启动按钮被单击事件
 37         private void btnstart_click(object sender, eventargs e)
 38         {
 39             // 创建并实例化ip终端结点
 40             ipendpoint ipendpoint =
 41                 new ipendpoint(ipaddress.parse(txtlocalip.text), convert.toint32(txtlocalport.text));
 42             // 实例化udp客户端(可用于实名发送和接收)
 43             myudpclient = new udpclient(ipendpoint);
 44 
 45             // 启动消息接收线程
 46             thread receivemessagethread = new thread(receivemessage);
 47             receivemessagethread.isbackground = true;
 48             receivemessagethread.start();
 49         }
 50 
 51         // 发送消息按钮被单击事件
 52         private void btnsendmsg_click(object sender, eventargs e)
 53         {
 54             // 判断是否为匿名发送
 55             if (chkanony.checked)
 56             {
 57                 // 匿名发送(套接字绑定的端口由系统自动分配)
 58                 anonyudpclient = new udpclient();
 59             }
 60 
 61             // 启动消息发送线程
 62             thread sendmessagethread = new thread(sendmessage);
 63             sendmessagethread.isbackground = true;
 64             sendmessagethread.start();
 65         }
 66 
 67         // 消息发送线程
 68         private void sendmessage()
 69         {
 70             // 创建并实例化ip终端结点
 71             ipendpoint ipendpoint =
 72                 new ipendpoint(ipaddress.parse(txtsendip.text), convert.toint32(txtsendport.text));
 73 
 74             // 准备发送的数据
 75             byte[] senddata = encoding.default.getbytes(txtsendmsg.text);
 76 
 77             // 判断是否为匿名发送
 78             if (chkanony.checked)
 79             {
 80                 // 匿名发送
 81                 anonyudpclient.send(senddata, senddata.length, ipendpoint);
 82                 // 关闭匿名udp客户端
 83                 anonyudpclient.close();
 84             }
 85             else
 86             {
 87                 // 实名发送
 88                 myudpclient.send(senddata, senddata.length, ipendpoint);
 89             }
 90 
 91         }
 92 
 93         // 消息接收线程
 94         private void receivemessage()
 95         {
 96             // 创建并实例化ip终端结点
 97             ipendpoint ipendpoint = new ipendpoint(ipaddress.any, 0);
 98 
 99             // 消息接收循环
100             while (true)
101             {
102                 try
103                 {
104                     // 同步阻塞接收消息
105                     byte[] getdata = myudpclient.receive(ref ipendpoint);
106                     string msg = encoding.default.getstring(getdata);
107                     // 显示消息到列表框中
108                     lstreceivemsg.invoke(showmsgcallback, ipendpoint.tostring() + ":" + msg);
109                 }
110                 catch (threadabortexception)
111                 {
112                     // 人为终止线程
113                 }
114                 catch (exception ex)
115                 {
116                     // 接收发生异常
117                     messagebox.show(ex.message);
118                 }
119             }
120         }
121 
122         // 显示消息回调方法
123         private void showmsg(string text)
124         {
125             lstreceivemsg.items.add(text);
126         }
127     }
128 }

7.udp广播和组播
 udp组播是采用的无连接,数据报的连接方式,所以是不可靠的.也就是数据能不能到达接受端和数据到达的顺序都是不能保证的.但是由于udp不用保证数据的可靠性,所有数据的传送速度是很快的.

 ip网络传输方式共分为单播,组播(多播),广播三种。

  ip组播通信需要一个特殊的组播地址,ip组播地址是一组d类ip地址,范围从224.0.0.0 到  239.255.255.255。其中还有很多地址是为特殊的目的保留的。224.0.0.0到224.0.0.255的地址最好不要用,因为他们大多是 为了特殊的目的保持的(比如igmp协议)

   相对于极度消耗网络带宽的广播来说(广播只能在内网广播),udp组播有了很大的优化,只有终端加入到了一个广播组,udp组播的数据才能被他接收到。

 

  1 using system;
  2 using system.net;
  3 using system.net.sockets;
  4 using system.text;
  5 using system.data;
  6 using system.drawing;
  7 using system.windows.forms;
  8 using system.threading;
  9 using system.collections.generic;
 10 using system.componentmodel;
 11 
 12 namespace 广播和组播
 13 {
 14     public partial class frmmain : form
 15     {
 16         // 显示消息回调
 17         private delegate void showmsgcallback(string text);
 18         private showmsgcallback showmsgcallback;
 19 
 20         private udpclient myudpclient;  // udp客户端
 21 
 22         // 窗体构造方法
 23         public frmmain()
 24         {
 25             initializecomponent();
 26         }
 27 
 28         // 窗体启动加载事件
 29         private void frmmain_load(object sender, eventargs e)
 30         {
 31             // 初始化回调
 32             showmsgcallback = new showmsgcallback(showmsg);
 33         }
 34 
 35         // 启动按钮被单击事件
 36         private void btnstart_click(object sender, eventargs e)
 37         {
 38             // 创建并实例化ip终端结点
 39             ipendpoint ipendpoint =
 40                 new ipendpoint(ipaddress.parse(txtlocalip.text), convert.toint32(txtlocalport.text));
 41             // 实例化udp客户端(可用于实名发送和接收)
 42             myudpclient = new udpclient(ipendpoint);
 43 
 44             // 判断是否加入组播
 45             if (chkjoinmutlibroadcast.checked)
 46             {
 47                 // 加入组播,并设置路由器最大转发次数
 48                 myudpclient.joinmulticastgroup(ipaddress.parse(txtmutlibroadcastip.text), 50);
 49             }
 50 
 51             // 启动消息接收线程
 52             thread receivemessagethread = new thread(receivemessage);
 53             receivemessagethread.isbackground = true;
 54             receivemessagethread.start();
 55         }
 56 
 57         // 发送消息按钮被单击事件
 58         private void btnsendmsg_click(object sender, eventargs e)
 59         {
 60             // 创建ip终端结点
 61             ipendpoint ipendpoint;
 62 
 63             // 判断消息发送类型
 64             if (chkbroadcast.checked)
 65             {
 66                 // 广播模式(由系统自动提供广播地址)
 67                 ipendpoint = new ipendpoint(ipaddress.broadcast, 33333);
 68             }
 69             else
 70             {
 71                 // 组播模式
 72                 ipendpoint = new ipendpoint(ipaddress.parse(txtsendmutlibroadcastip.text), 33333);
 73             }
 74 
 75             // 准备发送的数据
 76             byte[] senddata = encoding.default.getbytes(txtsendmsg.text);
 77             myudpclient.send(senddata, senddata.length, ipendpoint);
 78         }
 79 
 80         // 消息接收线程
 81         private void receivemessage()
 82         {
 83             // 创建并实例化ip终端结点
 84             ipendpoint ipendpoint = new ipendpoint(ipaddress.any, 0);
 85 
 86             // 消息接收循环
 87             while (true)
 88             {
 89                 try
 90                 {
 91                     // 同步阻塞接收消息
 92                     byte[] getdata = myudpclient.receive(ref ipendpoint);
 93                     string msg = encoding.default.getstring(getdata);
 94                     // 显示消息到列表框中
 95                     lstreceivemsg.invoke(showmsgcallback, ipendpoint.tostring() + ":" + msg);
 96                 }
 97                 catch (threadabortexception)
 98                 {
 99                     // 人为终止线程
100                 }
101                 catch (exception ex)
102                 {
103                     // 接收发生异常
104                     messagebox.show(ex.message);
105                 }
106             }
107         }
108 
109         // 显示消息回调方法
110         private void showmsg(string text)
111         {
112             lstreceivemsg.items.add(text);
113         }
114     }
115 }

8.局域网聊天室

  1 using system;
  2 using system.net;
  3 using system.net.sockets;
  4 using system.text;
  5 using system.data;
  6 using system.drawing;
  7 using system.windows.forms;
  8 using system.threading;
  9 using system.collections.generic;
 10 using system.componentmodel;
 11 
 12 namespace 局域网聊天室
 13 {
 14     public partial class frmserver : form
 15     {
 16         // 添加客户端回调
 17         private delegate void addnewclientcallback(string endpoint);
 18         private addnewclientcallback addnewclientcallback;
 19         // 显示接收消息回调
 20         private delegate void showreceivemsgcallback(string text);
 21         private showreceivemsgcallback showreceivemsgcallback;
 22         // 删除客户端回调
 23         private delegate void deleteclientcallback(int index);
 24         private deleteclientcallback deleteclientcallback;
 25 
 26         // * 网络连接相关 *
 27         private tcplistener mytcplistener;  // tcp连接侦听器
 28         private tcpclient tcpclient;              // tcp客户端
 29         private thread tcpclientacceptthread;   // 客户端连接监听线程
 30         private thread receivemsgthread;      // 接收消息线程
 31         private dictionary<string, socket> clientsocketdic;      // 保存客户端终端信息与socket字典
 32 
 33         // 窗体构造方法
 34         public frmserver()
 35         {
 36             initializecomponent();
 37         }
 38 
 39         // 窗体启动加载事件
 40         private void frmserver_load(object sender, eventargs e)
 41         {
 42             // 初始化属性
 43             clientsocketdic = new dictionary<string, socket>();
 44 
 45             // 初始化回调
 46             showreceivemsgcallback = new showreceivemsgcallback(showreceivemsg);
 47             addnewclientcallback = new addnewclientcallback(addnewclient);
 48             deleteclientcallback = new deleteclientcallback(deleteclient);
 49         }
 50 
 51         // 启动服务端按钮被单击事件
 52         private void btnstart_click(object sender, eventargs e)
 53         {
 54             try
 55             {
 56                 // 创建并实例化ip终端结点
 57                 ipendpoint ipendpoint =
 58                     new ipendpoint(ipaddress.parse(txtserverip.text), int.parse(txtserverport.text));
 59                 // 实例化tcp连接侦听器
 60                 mytcplistener = new tcplistener(ipendpoint);
 61                 // 启动tcp连接侦听器
 62                 mytcplistener.start();
 63                 // 创建并启动tcp连接侦听接受线程
 64                 tcpclientacceptthread = new thread(tcpclientaccept);
 65                 tcpclientacceptthread.isbackground = true;
 66                 tcpclientacceptthread.start();
 67                 // 修改控件状态
 68                 btnstart.enabled = false;
 69             }
 70             catch (exception ex)
 71             {
 72                 messagebox.show(ex.message);
 73             }
 74         }
 75 
 76         // tcp连接侦听接受线程
 77         private void tcpclientaccept()
 78         {
 79             try
 80             {
 81                 // 循环接收
 82                 while (true)
 83                 {
 84                     // 接收tcp客户端
 85                     tcpclient = mytcplistener.accepttcpclient();
 86                     // 实例化并启动接收消息线程
 87                     receivemsgthread = new thread(receivemsg);
 88                     receivemsgthread.isbackground = true;
 89                     receivemsgthread.start();
 90                     // 将客户端终端信息加入列表
 91                     lstclient.invoke(addnewclientcallback, tcpclient.client.remoteendpoint.tostring());
 92                     // 将客户端加入字典
 93                     clientsocketdic.add(tcpclient.client.remoteendpoint.tostring(), tcpclient.client);
 94                 }
 95             }
 96             catch (threadabortexception)
 97             {
 98                 // 人为终止线程
 99             }
100             catch (exception ex)
101             {
102                 // 连接发生异常
103                 messagebox.show(ex.message);
104                 // 释放相关系统资源
105                 if (tcpclient != null)
106                     tcpclient.close();
107             }
108         }
109 
110         // 接收消息线程
111         private void receivemsg()
112         {
113             // 获取客户端终端信息
114             string endpoint = tcpclient.client.remoteendpoint.tostring();
115             // 获取绑定的网络数据流
116             networkstream ns = tcpclient.getstream();
117             // 循环接收消息
118             while (true)
119             {
120                 try
121                 {
122                     int readlen = tcpclient.available;
123                     if (readlen >= 0)
124                     {
125                         // 创建并实例化用于存放数据的字节数组
126                         byte[] getdata = new byte[1024];
127                         // 从网络数据流中读取数据
128                         ns.read(getdata, 0, getdata.length);
129                         // 将字节数组转换为文本形式
130                         string getmsg = encoding.default.getstring(getdata);
131                         // 读取长度为0表示客户端已掉线
132                         if (getmsg.replace("\0", "").length == 0)
133                         {
134                             for (int i = 0; i < lstclient.items.count; i++)
135                             {
136                                 // 从客户端列表删除客户端
137                                 if (string.equals(lstclient.items[i].tostring(), endpoint))
138                                 {
139                                     lstclient.invoke(deleteclientcallback, i);
140                                 }
141                             }
142 
143                             // 将客户端从字典中删除
144                             clientsocketdic.remove(endpoint);
145                             break;
146                         }
147                         // 将消息添加到接收消息列表中
148                         lstmsg.invoke(showreceivemsgcallback, endpoint + ":" + getmsg);
149                         // 向除该客户端外的所有客户端转发消息
150                         for (int i = 0; i < lstclient.items.count; i++)
151                         {
152                             // 判断是否不为该客户端
153                             if (!string.equals(lstclient.items[i].tostring(), endpoint))
154                             {
155                                 clientsocketdic[lstclient.items[i].tostring()].send(encoding.default.getbytes(endpoint + ":" + getmsg.replace("\0", "")));
156                             }
157                         }
158                     }
159                 }
160                 catch (threadabortexception)
161                 {
162                     // 捕捉到线程被终止异常则表示人为的断开tcp连接
163                     // 不需要弹出错误提示
164                 }
165                 catch (exception ex)
166                 {
167                     // 接收消息发生异常
168                     messagebox.show(ex.message);
169                     // 释放相关系统资源
170                     if (ns != null)
171                         ns.dispose();
172                     break;
173                 }
174             }
175         }
176 
177         // 添加客户端回调方法
178         private void addnewclient(string endpoint)
179         {
180             lstclient.items.add(endpoint);
181         }
182 
183         // 显示接收消息回调方法
184         private void showreceivemsg(string text)
185         {
186             lstmsg.items.add(text);
187         }
188 
189         // 删除客户端回调党法
190         private void deleteclient(int index)
191         {
192             lstclient.items.removeat(index);
193         }
194     }
195 }

9.webclient

 1 using system;
 2 using system.net;
 3 using system.text;
 4 using system.data;
 5 using system.drawing;
 6 using system.windows.forms;
 7 using system.threading;
 8 using system.collections.generic;
 9 using system.componentmodel;
10 
11 namespace web_client
12 {
13     public partial class frmmain : form
14     {
15         // 窗体构造方法
16         public frmmain()
17         {
18             initializecomponent();
19         }
20 
21         // 获取源码按钮被单击事件
22         private void btngetsource_click(object sender, eventargs e)
23         {
24             // 创建并实例化 webclient 对象
25             webclient webclient = new webclient();
26             // 取消代理设置(默认为开启,会造成程序假死)
27             webclient.proxy = null;
28             // 获取网页源码
29             txtsource.text = webclient.downloadstring(txtwebaddress.text);
30         }
31 
32         // 同步下载按钮被单击事件
33         private void btnsyncdownload_click(object sender, eventargs e)
34         {
35             // 创建并实例化 webclient 对象
36             webclient webclient = new webclient();
37             // 取消代理设置(默认为开启,会造成程序假死)
38             webclient.proxy = null;
39             // 同步下载文件
40             webclient.downloadfile(txtremotepath.text, txtlocalpath.text);
41             messagebox.show("同步下载完成!");
42         }
43 
44         // 异步下载按钮被单击事件
45         private void btnasyncdownload_click(object sender, eventargs e)
46         {
47             // 创建并实例化 webclient 对象
48             webclient webclient = new webclient();
49             // 取消代理设置(默认为开启,会造成程序假死)
50             webclient.proxy = null;
51             // 关联事件
52             webclient.downloadfilecompleted += new asynccompletedeventhandler(webclient_downloadfilecompleted);
53             webclient.downloadprogresschanged += new downloadprogresschangedeventhandler(webclient_downloadprogresschanged);
54             // 开始异步下载文件
55             webclient.downloadfileasync(new uri(txtremotepath.text), txtlocalpath.text);
56         }
57 
58         // 异步下载文件进度改变事件
59         private void webclient_downloadprogresschanged(object sender, downloadprogresschangedeventargs e)
60         {
61             //e.bytesreceived;    // 已下载字节数
62             //e.totalbytestoreceive;  // 总下载字节数
63             // 可直接调用参数中的已下载百分比
64             pgdownload.value = e.progresspercentage;
65         }
66 
67         // 异步下载文件完成事件
68         private void webclient_downloadfilecompleted(object sender, asynccompletedeventargs e)
69         {
70             messagebox.show("异步下载完成!");
71         }
72     }
73 }

项目:

局域网:

1.tcp

    

  1 using system;
  2 using system.drawing;
  3 using system.windows.forms;
  4 using system.net.sockets;
  5 
  6 namespace chatting
  7 {
  8     public partial class mainform : form
  9     {
 10 
 11         public mainform()
 12         {
 13             initializecomponent();
 14         }
 15 
 16         socketfunc socket;
 17         system.action<string> receiveaction;
 18         system.action accessaction;
 19 
 20         private void mainform_load(object sender, eventargs e)
 21         {
 22             //异步建立连接回调
 23             accessaction = () =>
 24             {
 25                 this.invoke((methodinvoker)delegate()
 26                 {
 27                     lblfriendip.visible = false;
 28                     txtip.visible = false;
 29                     btnconnect.visible = false;
 30                     btnwaitaccess.visible = false;
 31 
 32                     string friendip = socket.communicatesocket.remoteendpoint.tostring();
 33                     lblstate.text = string.format("连接成功. 对方ip:{0}", friendip);
 34 
 35                     try
 36                     {
 37                         socket.receive(receiveaction);
 38                     }
 39                     catch (exception exp)
 40                     {
 41                         messagebox.show(exp.message, "错误");
 42                     }
 43                 });
 44 
 45             };
 46             //异步接收消息回调
 47             receiveaction = msg =>
 48             {
 49                 txtgetmsg.invoke((methodinvoker)delegate()
 50                 {
 51                     updategetmsgtextbox(false, msg, color.red);
 52                 });
 53             };
 54         }
 55 
 56         private void btnwaitaccess_click(object sender, eventargs e)
 57         {
 58             this.socket = new serversocket();
 59             try
 60             {
 61                 this.socket.access("", this.accessaction);
 62             }
 63             catch (exception ecp)
 64             {
 65                 messagebox.show(ecp.message, "错误");
 66             }
 67 
 68             lblstate.text = "等待对方连接...";
 69         }
 70 
 71         private void btnconnect_click(object sender, eventargs e)
 72         {
 73             this.socket = new clientsocket();
 74             try
 75             {
 76                 this.socket.access(txtip.text, this.accessaction);
 77             }
 78             catch (exception ecp)
 79             {
 80                 messagebox.show(ecp.message, "错误");
 81             }
 82             lblstate.text = "正在连接对方...";
 83         }
 84 
 85         private void btnsendmsg_click(object sender, eventargs e)
 86         {
 87             string message = txtsendmsg.text.trim();
 88             if (string.isnullorempty(message))
 89             {
 90                 messagebox.show("消息内容不能为空!", "错误");
 91                 txtsendmsg.focus();
 92                 return;
 93             }
 94 
 95             try
 96             {
 97                 socket.send(message);
 98             }
 99             catch(exception ecp)
100             {
101                 messagebox.show(ecp.message, "错误");
102                 return;
103             }
104 
105             updategetmsgtextbox(true, message, color.blue);
106             txtsendmsg.text = "";
107         }
108 
109         private void updategetmsgtextbox(bool sendmsg, string message, color color)
110         {
111             string appendtext;
112             if (sendmsg == true)
113             {
114                 appendtext = "me:           " + system.datetime.now.tostring()
115                     + environment.newline
116                     + message + environment.newline;
117             }
118             else
119             {
120                 appendtext = "friend:           " + system.datetime.now.tostring()
121                     + environment.newline
122                     + message + environment.newline;
123             }
124             int txtgetmsglength = txtgetmsg.text.length;
125             txtgetmsg.appendtext(appendtext);
126             txtgetmsg.select(txtgetmsglength, appendtext.length - environment.newline.length*2 -message.length);
127             txtgetmsg.selectioncolor = color;
128 
129             txtgetmsg.scrolltocaret();
130         }
131     }
132 }
  1 using system;
  2 using system.net;
  3 using system.net.sockets;
  4 using system.text;
  5 
  6 namespace chatting
  7 {
  8     public abstract class socketfunc
  9     {
 10         //不管是服务端还是客户端, 建立连接后用这个socket进行通信
 11         public socket communicatesocket = null;
 12 
 13         //服务端和客户端建立连接的方式稍有不同, 子类会重载
 14         public abstract void access(string ip, system.action accessaciton);
 15 
 16         //发送消息的函数
 17         public void send(string message)
 18         {
 19             if (communicatesocket.connected == false)
 20             {
 21                 throw new exception("还没有建立连接, 不能发送消息");
 22             }
 23             byte[] msg = encoding.utf8.getbytes(message);
 24             communicatesocket.beginsend(msg,0, msg.length, socketflags.none,
 25                 ar => {
 26                 
 27                 }, null);
 28         }
 29 
 30         //接受消息的函数
 31         public void receive(system.action<string> receiveaction)
 32         {
 33             //如果消息超过1024个字节, 收到的消息会分为(总字节长度/1024 +1)条显示
 34             byte[] msg = new byte[1024];
 35             //异步的接受消息
 36             communicatesocket.beginreceive(msg, 0, msg.length, socketflags.none,
 37                 ar => {
 38                     //对方断开连接时, 这里抛出socket exception
 39                     //an existing connection was forcibly closed by the remote host 
 40                         communicatesocket.endreceive(ar); 
 41                     receiveaction(encoding.utf8.getstring(msg).trim('\0',' '));
 42                     receive(receiveaction);
 43                 }, null);
 44         }
 45     }
 46 
 47 
 48     public class serversocket:socketfunc
 49     {
 50         //服务端重载access函数
 51         public override void access(string ip, system.action accessaciton)
 52         {
 53             socket serversocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
 54             //本机预使用的ip和端口
 55             ipendpoint serverip = new ipendpoint(ipaddress.any, 9050);
 56             //绑定服务端设置的ip
 57             serversocket.bind(serverip);
 58             //设置监听个数
 59             serversocket.listen(1);
 60             //异步接收连接请求
 61             serversocket.beginaccept(ar =>
 62                 {
 63                     base.communicatesocket = serversocket.endaccept(ar);
 64                     accessaciton();
 65                 }, null);
 66         }
 67     }
 68 
 69     public class clientsocket:socketfunc
 70     {
 71         //客户端重载access函数
 72         public override void access(string ip, system.action accessaciton)
 73         {
 74             base.communicatesocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
 75             base.communicatesocket.bind(new ipendpoint(ipaddress.any, 9051));
 76             
 77             //服务器的ip和端口
 78             ipendpoint serverip;
 79             try
 80             {
 81                 serverip = new ipendpoint(ipaddress.parse(ip), 9050);
 82             }
 83             catch
 84             {
 85                 throw new exception(string.format("{0}不是一个有效的ip地址!", ip));
 86             }
 87             
 88             //客户端只用来向指定的服务器发送信息,不需要绑定本机的ip和端口,不需要监听
 89             try
 90             {
 91                 base.communicatesocket.beginconnect(serverip, ar =>
 92                 {
 93                     accessaciton();
 94                 }, null);
 95             }
 96             catch
 97             {
 98                 throw new exception(string.format("尝试连接{0}不成功!", ip));
 99             }
100         }
101     }
102 }

 2.udp

 

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.net;
 10 using system.net.sockets;
 11 using italktradition.code;
 12 
 13 
 14 namespace italktradition
 15 {
 16     public partial class frmuser : form
 17     {
 18         #region field
 19 
 20         /// <summary>
 21         /// 在非主线程是对控件操作
 22         /// </summary>
 23         /// <param name="host"></param>
 24         private delegate void myinvoke(string host);
 25 
 26         /// <summary>
 27         /// 充当服务器 进行监听接收
 28         /// </summary>
 29         private socketudpserver udpserver;
 30 
 31         /// <summary>
 32         /// 充当客户端
 33         /// </summary>
 34         private socketudpclient udpclient;
 35 
 36         #endregion
 37 
 38         #region contructor
 39 
 40         /// <summary>
 41         /// 构造函数
 42         /// </summary>
 43         public frmuser()
 44         {
 45             initializecomponent();
 46             init();
 47         }
 48 
 49         #endregion
 50 
 51         #region method
 52 
 53         /// <summary>
 54         /// 初始化数据
 55         /// </summary>
 56         private void init()
 57         {
 58             lanlist.currentlanlist = new list<laninfo>();
 59             this.text = "当前局域网内在线用户";
 60             this.udpserver = socketudpserver.instance;
 61             this.udpserver.onlinecomplete += new socketudpserver.oncompletehander(this.online_event);
 62             this.udpserver.downlinecomplete += new socketudpserver.oncompletehander(this.downline_event);
 63             this.udpserver.errorappear += new socketudpserver.oncompletehander(this.error_event);
 64             this.udpserver.listen();
 65             this.udpclient = new socketudpclient();
 66             this.udpclient.broadcast(datagramtype.online);
 67 
 68         }
 69 
 70         /// <summary>
 71         /// 上线增加用户
 72         /// </summary>
 73         /// <param name="host">用户主机</param>
 74         private void adduser(string host)
 75         {
 76             this.ilbuserlist.items.add(host);
 77         }
 78 
 79         /// <summary>
 80         /// 下线减少用户
 81         /// </summary>
 82         /// <param name="host">用户主机在列表的序号 懒了以下 应该将回调的委托参数定义为int的,这里用了string 到程序需要转化为int</param>
 83         private void removeuser(string hostindex)
 84         {
 85             this.ilbuserlist.items.removeat(convert.toint32(hostindex));
 86         }
 87 
 88         #endregion
 89 
 90         #region event
 91 
 92         /// <summary>
 93         /// 上线事件
 94         /// </summary>
 95         /// <param name="socket"></param>
 96         /// <param name="e"></param>
 97         private void online_event(socketudpserver socket, eventargs e)
 98         {
 99             string host = socket.message;
100             //如果该上线的用户在局域网列表中不存在
101             if (!lanlist.currentlanlist.exists(x => x.host == host))
102             {
103                 while (!this.ishandlecreated) ;
104                 this.ilbuserlist.invoke(new myinvoke(this.adduser), host);
105                 //将上线用户添加进静态的局域网列表
106                 lanlist.currentlanlist.add(new laninfo()
107                 {
108                     host = host,
109                     state = talkstate.waiting,
110                     remoteendpoint = socket.remoteendpoint
111                 });
112             }
113         }
114 
115         /// <summary>
116         /// 下线事件
117         /// </summary>
118         /// <param name="socket"></param>
119         /// <param name="e"></param>
120         private void downline_event(socketudpserver socket, eventargs e)
121         {
122             string host = socket.message;
123             if (lanlist.currentlanlist.exists(x => x.host == host))
124             {
125                 ///判断是否是自己的主机下线 如果是自己的 则不需要操作
126                 if (string.compare(dns.gethostname(), host) != 0)
127                 {
128                     this.ilbuserlist.invoke(new myinvoke(this.removeuser), lanlist.currentlanlist.findindex(x => x.host == host).tostring());
129                     //将该用户从局域网列表中移除
130 
131                     lanlist.currentlanlist.removeall(x => x.host == host);
132                 }
133             }
134         }
135 
136         /// <summary>
137         /// 出现错误的事件
138         /// </summary>
139         /// <param name="socket"></param>
140         /// <param name="e"></param>
141         private void error_event(socketudpserver socket, eventargs e)
142         {
143             messagebox.show(socket.message);
144         }
145 
146         private void ilbuserlist_doubleclick(object sender, eventargs e)
147         {
148             //xtramessagebox.show(ilbuserlist.selecteditem.tostring());
149             string host = ilbuserlist.selecteditem.tostring();
150             ///打开窗口 设置为正在交谈
151             lanlist.settalkstate(host, talkstate.talking);
152             (new frmtalk(host)).show();
153         }
154 
155         /// <summary>
156         /// 窗体关闭事 进行下线广播
157         /// </summary>
158         /// <param name="sender"></param>
159         /// <param name="e"></param>
160         private void frmuser_formclosed(object sender, formclosedeventargs e)
161         {
162             this.udpclient.broadcast(datagramtype.downline);
163             this.udpserver.stop();
164             application.exit();
165         }
166 
167         /// <summary>
168         /// 刷新按钮
169         /// </summary>
170         /// <param name="sender"></param>
171         /// <param name="e"></param>
172         private void btnrefresh_click(object sender, eventargs e)
173         {
174             //刷新  情况列表中的数据  重新上线广播
175             this.ilbuserlist.items.clear();
176             lanlist.currentlanlist.clear();
177             this.udpclient.broadcast(datagramtype.online);
178         }
179 
180 
181 
182         #endregion
183 
184 
185     }
186 }

双击listbox内的用户名会出现下面的聊天窗口

    

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.net;
 10 using system.net.sockets;
 11 using italktradition.code;
 12 
 13 
 14 namespace italktradition
 15 {
 16     public partial class frmtalk : form
 17     {
 18         #region field
 19 
 20         /// <summary>
 21         /// 自己的socket 充当服务器  接收消息
 22         /// </summary>
 23         private socketudpserver selfsocket = null;
 24         /// <summary>
 25         /// 对话的socket
 26         /// </summary>
 27         private socketudpclient tallsocket = null;
 28         /// <summary>
 29         /// 谈话对方的局域网信息
 30         /// </summary>
 31         private laninfo talklan = null;
 32         /// <summary>
 33         /// 当前用户主机
 34         /// </summary>
 35         private string currentuserhost = "";
 36 
 37         /// <summary>
 38         /// 对控件操作 在非主线程下需要调用此代理
 39         /// </summary>
 40         private delegate void myinvoke(string user, string message);
 41 
 42         #endregion
 43 
 44         #region constructor
 45 
 46         /// <summary>
 47         /// 通过远端主机名打开窗体
 48         /// </summary>
 49         /// <param name="host"></param>
 50         public frmtalk(string host)
 51         {
 52             initializecomponent();
 53             if (this.talklan == null)
 54             {
 55                 this.talklan = lanlist.currentlanlist.find(x => x.host == host);
 56             }
 57 
 58             this.currentuserhost = dns.gethostname();
 59             this.text = "正在和" + host + "聊天中";
 60             this.initializion();
 61         }
 62 
 63         /// <summary>
 64         /// 通过远端 端点打开窗体
 65         /// </summary>
 66         /// <param name="remotepoint"></param>
 67         public frmtalk(endpoint remotepoint)
 68         {
 69             this.talklan = lanlist.currentlanlist.find(x => string.compare(x.remoteendpoint.tostring(), remotepoint.tostring()) == 0);
 70             (new frmtalk(talklan.host)).show();
 71         }
 72 
 73         #endregion
 74 
 75         #region method
 76 
 77         /// <summary>
 78         /// 初始化方法
 79         /// </summary>
 80         private void initializion()
 81         {
 82             this.selfsocket = socketudpserver.instance;
 83             ///绑定收到信息事件
 84             this.selfsocket.onchatcomplete += new socketudpserver.oncompletehander(this.receiveevent);
 85             //给谈话的socket初始化endpoint
 86             this.tallsocket = new socketudpclient(this.talklan.remoteendpoint);
 87 
 88         }
 89 
 90         /// <summary>
 91         /// 加载未读的信息
 92         /// </summary>
 93         private void loadunreadmessage()
 94         {
 95             queue<messageinfo> queque = queuemessage.getandremove(talklan.host);
 96             messageinfo messageinfo = null;
 97             if (queque != null)
 98             {
 99                 while (queque.count > 0)
100                 {
101                     //出队列
102                     messageinfo = queque.dequeue();
103                     this.lbxmessage.items.add(talklan.host + ":" + messageinfo.receivetime.tostring("yyyy-mm-dd hh:mm:ss"));
104                     this.lbxmessage.items.add(messageinfo.message);
105                 }
106             }
107         }
108 
109         /// <summary>
110         /// 添加一行 在listboxcontrol中
111         /// </summary>
112         /// <param name="name">显示的用户</param>
113         /// <param name="message">消息</param>
114         private void addline(string name, string message)
115         {
116             this.lbxmessage.items.add(name + ":" + datetime.now.tostring("yyyy-mm-dd hh:mm:ss"));
117             this.lbxmessage.items.add(message);
118         }
119 
120         /// <summary>
121         /// 发送信息 由键盘回车和发送按钮调用
122         /// </summary>
123         private void sendmessage()
124         {
125             try
126             {
127                 string message = this.meminput.text;
128                 if (string.isnullorempty(message))
129                 {
130                     messagebox.show("发送信息不能为空");
131                 }
132                 else
133                 {
134                     this.tallsocket.send(message);
135                     this.addline("我", message);
136                     this.meminput.text = "";
137                 }
138             }
139             catch (exception ex)
140             {
141                 messagebox.show(ex.message);
142             }
143         }
144 
145         #endregion
146 
147         #region event
148 
149         /// <summary>
150         /// 表单加载
151         /// </summary>
152         /// <param name="sender"></param>
153         /// <param name="e"></param>
154         private void frmtalk_load(object sender, eventargs e)
155         {
156             this.loadunreadmessage();
157         }
158 
159         /// <summary>
160         /// 接收信息回调事件
161         /// </summary>
162         /// <param name="socket"></param>
163         /// <param name="e"></param>
164         private void receiveevent(socketudpserver socket, eventargs e)
165         {
166             //判断 远端的网络端点是否是当前的 打开的窗体
167             if (string.compare(this.talklan.remoteendpoint.tostring(), socket.remoteendpoint.tostring()) == 0)
168             {
169                 this.lbxmessage.invoke(new myinvoke(this.addline), this.talklan.host, socket.message);
170             }
171         }
172 
173         /// <summary>
174         /// 信息发送按钮
175         /// </summary>
176         /// <param name="sender"></param>
177         /// <param name="e"></param>
178         private void btnsend_click(object sender, eventargs e)
179         {
180             this.sendmessage();
181         }
182 
183 
184 
185         private void frmtalk_formclosed(object sender, formclosedeventargs e)
186         {
187             //将其设置为非交谈状态
188             lanlist.settalkstate(talklan.host, talkstate.waiting);
189         }
190 
191         private void meminput_keydown(object sender, keyeventargs e)
192         {
193             ///按下回车事件
194             if (e.keycode == keys.enter)
195             {
196                 this.sendmessage();
197             }
198         }
199 
200 
201         #endregion
202     }
203 }
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appsettings>
    <!--应用程序的名称-->
    <add key="appname" value="简单的局域网聊天" />
    <!--用户文件的根目录-->
    <add key="rootdir" value="e:\doc\" />
    <!--程序监听的端口-->
    <add key="port" value="8001"/>
  </appsettings>

</configuration>

--------------------

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using chat1.bll;
10 
11 namespace chat1
12 {
13     public partial class form1 : form
14     {
15         p2pserver serverobj = new p2pserver();
16         public form1()
17         {
18             initializecomponent();
19         }
20 
21         private void form1_load(object sender, eventargs e)
22         {
23             try
24             {
25                 serverobj.connectevent += serverobj_connectenent;
26                 //订阅连接事件
27                 serverobj.receiveevent += serverobj_receiveenent;
28                 //订阅接收数据事件
29                 serverobj.listen(convert.toint32(textbox1.text));  //启动监听
30             }
31             catch (exception ex)
32             {
33                 messagebox.show("加载失败:" + ex.message);
34             }
35         }
36 
37         private void serverobj_connectenent()
38         {
39             try
40             {
41                 if (invokerequired)
42                 {
43                     p2pserver.connectdelegate update = serverobj_connectenent;
44 
45                     invoke(update);
46                 }
47                 else
48                 {
49                     listbox1.items.add("连接成功");
50                 }
51             }
52             catch (exception ex)
53             {
54                 messagebox.show("处理连接事件方法错误:" + ex.message);
55             }
56         }
57 
58         private void serverobj_receiveenent(string message)
59         {
60             try
61             {
62                 if (invokerequired)
63                 {
64                     p2pserver.receivedelegate update = serverobj_receiveenent;
65 
66                     invoke(update, new object[] { message });
67                 }
68                 else
69                 {
70                     listbox1.items.add(message);//添加到显示栏
71 
72                     serverobj.send(message);
73                 }
74             }
75             catch (exception ex)
76             {
77                 messagebox.show(@"处理事件方法错误:" + ex.message);
78             }
79         }
80 
81         //private void form1_formclosing(object sender, formclosingeventargs e)
82         //{
83         //    close();
84         //}
85 
86     }
87 }
 1 using system;
 2 using system.collections.generic;
 3 using system.io;
 4 using system.linq;
 5 using system.net;
 6 using system.net.sockets;
 7 using system.text;
 8 using system.threading;
 9 
10 namespace chat1.bll
11 {
12     class p2pserver
13     {
14         public tcplistener listenobj;
15         public dictionary<string, tcpclient> clientmem = new dictionary<string, tcpclient>(); //客户列表一定要初始化,new
16 
17         private thread listenthread;
18 
19         public delegate void connectdelegate(); //连接成功后处理事件的方法类型
20         public event connectdelegate connectevent;//连接事件
21 
22         public delegate void receivedelegate(string message); //连接数据后处理事件方法类型
23         public event receivedelegate receiveevent;  //接受数据事件
24 
25         public void listen(int port) //监听方法,启动监线程
26         {
27             ipaddress[] localip = dns.gethostaddresses(dns.gethostname()); //通过主机名获得本地ip
28             listenobj = new tcplistener(localip[1], port);//监听对象
29             listenthread = new thread(listenclient);   //监听客户
30             listenthread.start();
31         }
32 
33         private void listenclient()
34         {
35             while (true)      //一直监听,可以有多个客户端请求连接
36             {
37                 listenobj.start();
38                 tcpclient acceptclientobj = listenobj.accepttcpclient(); //接收挂起的连接请求,这是一个组色的方法
39                 this.connectevent();//触发连接事件
40 
41                 thread receivethread = new thread(receiver); //这个线程处理接受的数据
42                 string connecttime = datetime.now.tostring();
43                 receivethread.name = connecttime;
44                 clientmem.add(connecttime, acceptclientobj);  //将客户添加到列表
45 
46                 receivethread.start();//
47             }
48         }
49 
50         private void receiver()
51         {     //所有的
52             while (true)
53             {
54                 networkstream ns = clientmem[thread.currentthread.name].getstream();
55 
56                 streamreader sr = new streamreader(ns);
57 
58                 string message = sr.readline();
59 
60                 receiveevent(message);// 接收过数据  就触发接收信息的事件
61             }
62         }
63 
64         public void send(string message)
65         {
66             foreach (keyvaluepair<string, tcpclient> keyvaluepair in clientmem)   //向所有客户发送数据
67             {
68                 if (keyvaluepair.value == null || keyvaluepair.value.connected == false)
69                 {
70                     clientmem.remove(keyvaluepair.key);   // 删除断开的连接
71 
72                 }
73                 if (keyvaluepair.value != null)
74                 {
75                     networkstream ns = keyvaluepair.value.getstream(); //得到网路流
76                     streamwriter sw = new streamwriter(ns);
77                     sw.writeline(message);
78 
79                     sw.flush(); //刷新数据流
80                     ns.flush();
81                 }
82             }
83         }
84     }
85 }

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using chat.bll;
 10 
 11 namespace chat
 12 {
 13     public partial class form1 : form
 14     {
 15         private p2pclient clientobj = new p2pclient();//客户对象 一定要new
 16         public form1()
 17         {
 18             initializecomponent();
 19         }
 20 
 21         private void form1_load(object sender, eventargs e)
 22         {
 23             sendbutton.enabled = false;  //没有连接不允许发送数据
 24             this.acceptbutton = sendbutton;
 25         }
 26 
 27         private void clientbutton_click(object sender, eventargs e)
 28         {
 29             string nickname = tbname.text;
 30             string ip = tbip.text;
 31             string port = tbport.text;
 32 
 33             if (string.isnullorempty(nickname) || string.isnullorempty(ip) || string.isnullorempty(port))
 34             {
 35                 messagebox.show("请讲昵称、ip填写完整");
 36                 return;
 37             }
 38             try
 39             {
 40                 clientobj.sendconnection(ip, convert.toint32(port)); //连接
 41                 clientobj.receiveevent += new p2pclient.receivedelegate(clientobj_receiveevent);
 42                 clientobj.send(tbname.text + "登陆成功!");
 43 
 44                 sendbutton.enabled = true;
 45                 clientbutton.enabled = false;
 46             }
 47             catch (exception ex)
 48             {
 49                 messagebox.show("连接时出错:" + ex.message);
 50                 return;
 51 
 52             }
 53         }
 54 
 55         private void clientobj_receiveevent(string receivedata)
 56         {
 57             try
 58             {
 59                 if (this.invokerequired) //指示是否需要在这个线程上调用方法
 60                 {
 61                     p2pclient.receivedelegate update = new p2pclient.
 62                         receivedelegate(clientobj_receiveevent); //把信息传送给控件线程是重复调用该方法就会调用else
 63                     this.invoke(update, new object[] { receivedata });
 64                 }
 65                 else
 66                 {
 67                     listbox1.items.add(receivedata);  //添加数据
 68                 }
 69             }
 70             catch (exception ex)
 71             {
 72                 messagebox.show("接收数据错误:" + ex.message);
 73                 return;
 74             }
 75         }
 76 
 77         private void sendbutton_click(object sender, eventargs e)
 78         {
 79             try
 80             {
 81                 if (string.isnullorempty(textbox1.text))
 82                 {
 83                     return;
 84                 }
 85                 clientobj.send(tbname.text + "说: \n");  //发送信息
 86                 clientobj.send("      " + textbox1.text);
 87                 textbox1.clear();
 88             }
 89             catch (exception ex)
 90             {
 91                 messagebox.show("发送数据错误" + ex.message);
 92                 return;
 93             }
 94         }
 95 
 96         //private void form1_formclosing(object sender, formclosingeventargs e)
 97         //{
 98         //    this.close();
 99         //}
100 
101     }
102 }
 1 using system;
 2 using system.collections.generic;
 3 using system.io;
 4 using system.linq;
 5 using system.net;
 6 using system.net.sockets;
 7 using system.text;
 8 using system.threading;
 9 
10 namespace chat.bll
11 {
12     class p2pclient
13     {//下载于51aspx.com
14         public tcpclient tcpclientobj; //收发数据
15         private thread receivetthread; //接收数据的线程
16 
17         public delegate void receivedelegate(string receivedata); //处理接收数据事件的方法类型
18 
19         public event receivedelegate receiveevent;
20 
21         public void sendconnection(string ip, int port)
22         {
23             ipaddress ipaddress = ipaddress.parse(ip);//转为ip地址后在连接会加快速度
24             tcpclientobj = new tcpclient(); //连接客户端
25             tcpclientobj.connect(ipaddress, port); //连接
26 
27             receivetthread = new thread(reveiver);  //启动线程
28             receivetthread.start();
29         }
30 
31         private void reveiver()
32         {//下载于51aspx.com
33             while (true)
34             {
35                 networkstream ns = this.tcpclientobj.getstream();
36 
37                 streamreader sr = new streamreader(ns);
38                 string receivedata = sr.readline();
39                 receiveevent(receivedata); //触发事件
40             }
41         }
42 
43         public void send(string message) //发送信息
44         {
45             if (tcpclientobj == null)
46             {
47                 return;
48             }
49             networkstream ns = this.tcpclientobj.getstream();   //得到网络流
50 
51             streamwriter sw = new streamwriter(ns);
52             sw.writeline(message);
53             sw.flush();   //是所有的缓冲数据写入基础数据
54             ns.flush();
55         }
56     }
57 }

-------------------------------

 

广域网: 

 tcp例子:

  1 using system;
  2 using system.io;
  3 using system.net;
  4 using system.net.sockets;
  5 using system.text;
  6 using system.threading;
  7 using system.windows.forms;
  8 
  9 namespace mysocket
 10 {
 11     public partial class form1 : form
 12     {
 13         //服务器监听套接字
 14         private clientmanager clientmanage;
 15         private bool iswatching = true;
 16         private socket sokserver;
 17         //监听线程
 18         private thread thrserver;
 19 
 20         public form1()
 21         {
 22             initializecomponent();
 23             //防止新线程调用主线程卡死
 24             checkforillegalcrossthreadcalls = false;
 25         }
 26 
 27         //创建客户端管理类对象
 28 
 29         private void btnserstar_click(object sender, eventargs e)
 30         {
 31             //网络操作是很容易断开连接,所以一般要try catch
 32             try
 33             {
 34                 //创建一个socket实例
 35                 //第一个参数表示使用ipv4
 36                 //第二个参数表示发送的是数据流
 37                 //第三个参数表示使用的协议是tcp协议
 38                 sokserver = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
 39                 //获取ip地址局域网使用 ipv4,广域网使用外网ip
 40                 ipaddress ip = ipaddress.parse(txtserip.text.trim());
 41                 //创建一个网络通信节点,这个通信节点包含了ip地址,跟端口号。
 42                 //这里的端口我们设置为1029,这里设置大于1024,为什么自己查一下端口号范围使用说明。我默认为51111
 43                 var point = new ipendpoint(ip, int.parse(txtserport.text.trim()));
 44                 //socket绑定网路通信节点
 45                 sokserver.bind(point);
 46                 //    //设置监听队列 同一时间最多连几个   (对应界面的系统负荷)
 47                 sokserver.listen(convert.toint32(txtsermax.text));
 48                 //sokserver.accept()这个接收消息的方法会使线程卡死,所以要开启新线程
 49                 thrserver = new thread(watchconnection);
 50                 //设置为后台线程防止卡死
 51                 thrserver.isbackground = true;
 52                 thrserver.start();
 53                 //管理类对象实例化传入好友列表listbox控件和消息委托
 54                 clientmanage = new clientmanager(listchat, appendmsg);
 55                 appendmsg("开始监听~~~~!" + datetime.now);
 56             }
 57             catch (exception ex)
 58             {
 59                 messagebox.show("异常:" + ex.message + datetime.now);
 60                 appendmsg("异常:" + ex.message + "1" + datetime.now);
 61             }
 62         }
 63 
 64         private void watchconnection()
 65         {
 66             try
 67             {
 68                 while (iswatching) //注意该循环,服务端要持续监听,要不然一个客户端链接过后就无法链接第二个客户端了。
 69                 {
 70                     //开始监听客户端的消息
 71                     //负责通信的socket
 72                     socket sokmsg = sokserver.accept();
 73                     //加入通信管理类
 74                     // messagebox.show(sokmsg.remoteendpoint.tostring());
 75                     clientmanage.addclient(sokmsg);
 76                 }
 77             }
 78             catch (socketexception ex1)
 79             {
 80                 appendmsg("异常:" + ex1.message + "2" + datetime.now);
 81             }
 82             catch (exception ex)
 83             {
 84                 appendmsg("异常:" + ex.source + "@" + ex.message + "@" + ex.targetsite + "@" + ex.innerexception + "@" +
 85                           ex.data + "3" + datetime.now);
 86             }
 87         }
 88 
 89         private void appendmsg(string strmsg)
 90         {
 91             txtsetting.appendtext(strmsg + "\r\n");
 92         }
 93 
 94         private void btnserclose_click(object sender, eventargs e)
 95         {
 96             iswatching = false;
 97             sokserver.close();
 98         }
 99 
100         private void form1_load(object sender, eventargs e)
101         {
102             checkforillegalcrossthreadcalls = false;
103             int x = convert.toint32(txtsermax.text);
104         }
105 
106         private void btnsetclear_click(object sender, eventargs e)
107         {
108             txtsetting.text = "";
109         }
110 
111         private void btnsetsave_click(object sender, eventargs e)
112         {
113             using (
114                 var fsm = new filestream(path.getdirectoryname(application.executablepath) + "\\" + "服务器日志.txt",
115                     filemode.openorcreate, fileaccess.readwrite))
116             {
117                 byte[] newbuffer = encoding.utf8.getbytes(txtsetting.text);
118                 fsm.write(newbuffer, 0, newbuffer.length);
119             }
120         }
121         //刷新在线人数
122         private void timer1_tick(object sender, eventargs e)
123         {
124             txtonlinecount.text = listchat.items.count.tostring();
125         }
126     }
127 }
 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.threading.tasks;
 6 
 7 namespace mysocket
 8 {
 9     /// <summary>
10     /// 全局消息委托
11     /// </summary>
12     /// <param name="strmsg">消息</param>
13     public delegate void dgsendmsg(string strmsg);
14 }
  1 using system;
  2 using system.collections.generic;
  3 using system.linq;
  4 using system.net.sockets;
  5 using system.text;
  6 using system.threading;
  7 using system.threading.tasks;
  8 
  9 namespace mysocket
 10 {
 11     /// <summary>
 12     /// 客户端管理
 13     /// </summary>
 14     public class clientmanager
 15     {
 16         //好友列表控件
 17         private system.windows.forms.listbox listclient;
 18         //在服务器上显示消息的委托(全局)
 19         dgsendmsg dgsendmsg;
 20         //通信套接字key :客户端ip value :对应的通信套接字
 21         private dictionary<string, socket> clientsocket;
 22         // 通信套接字key :客户端ip value :用户名(由于没有添加数据库我们暂时这么模拟,下篇我会讲到)
 23         private dictionary<string, string> usersocket;
 24         public clientmanager()
 25         { }
 26         /// <summary>
 27         /// 客户端管理类
 28         /// </summary>
 29         /// <param name="lb">列表控件</param>
 30         /// <param name="dgsendmsg">显示消息</param>
 31         public clientmanager(system.windows.forms.listbox lb, dgsendmsg dgsendmsg)
 32         {
 33             //用户列表
 34             this.listclient = lb;
 35             //消息委托
 36             this.dgsendmsg = dgsendmsg;
 37             //通信字典
 38             clientsocket = new dictionary<string, socket>();
 39             //用户字典
 40             usersocket = new dictionary<string, string>();
 41         }
 42         #region  添加客户端通信套接字+ public void addclient(socket sokmsg)
 43         /// <summary>
 44         /// 添加通信套接字
 45         /// </summary>
 46         /// <param name="sokmag">负责通信的socket</param>
 47         public void addclient(socket sokmsg)
 48         {
 49             //获取客户端通信套接字
 50             string strendpoint = sokmsg.remoteendpoint.tostring();
 51             //通信套接字加入字典
 52             clientsocket.add(strendpoint, sokmsg);
 53             //sokserver.accept()这个接收消息的方法会使线程卡死,所以要开启新线程
 54             thread thrmag = new thread(recivemsg);
 55             //设置为后台线程防止卡死
 56             thrmag.isbackground = true;
 57             //开启线程 为新线程传入通信套接字参数
 58             thrmag.start(sokmsg);
 59             dgsendmsg(strendpoint + "成功连接上服务端~~~!" + datetime.now.tostring());
 60         }
 61         #endregion
 62         bool isreceing = true;
 63         #region void recivemsg(object sokmsgobj)    服务接收客户端消息
 64         /// <summary>
 65         /// 服务接收客户端消息
 66         /// </summary>
 67         /// <param name="sokmsgobj">客户端scoket</param>
 68         void recivemsg(object sokmsgobj)
 69         {
 70             socket sokmsg = null;
 71             try
 72             {
 73                 //sokmsg接收消息的socket
 74                 sokmsg = sokmsgobj as socket;
 75                 //创建接收消息的缓冲区   默认5m
 76                 byte[] arrmsg = new byte[5 * 1024 * 1024];
 77                 //循环接收
 78                 while (isreceing)
 79                 {
 80                     //接收到的真实消息存入缓冲区     并保存消息的真实长度(因为5m缓冲区不会全部用掉)
 81                     int reallength = sokmsg.receive(arrmsg);
 82                     //将缓冲区的真实数据转成字符串
 83                     string strmsg = encoding.utf8.getstring(arrmsg, 0, reallength);
 84                     //dgsendmsg(strmsg);
 85 
 86                     string[] msgtxt = strmsg.split('|');
 87                     //  msgtxt.length == 2说明用户第一次连入,我们必须记录他的ip并与用户对应起来,如果局域网聊天
 88                     //ip在同一网段两个客户端还可以互相找到, 如果广域网下只有通过服务器转接才能找到
 89                     if (msgtxt.length == 2)
 90                     {
 91                         //如果用户名已登录则强制下线
 92                         if (usersocket.values.contains(msgtxt[0]))
 93                         {
 94                             sokmsg.close();
 95                             return;
 96                         }
 97                         usersocket.add(sokmsg.remoteendpoint.tostring(), msgtxt[0]);
 98                         //显示列表
 99                         listclient.items.add(sokmsg.remoteendpoint + "---" + msgtxt[0] + @"---上线~\(≧▽≦)/~啦啦啦");
100                         continue;
101                     }
102                     sendmsgtoclient(strmsg);
103                 }
104             }
105             catch
106             {
107                 //连接出错说明客户端连接断开
108                 removeclient(sokmsg.remoteendpoint.tostring());
109             }
110         }
111         #endregion
112         /// <summary>
113         /// 移除下线用户信息
114         /// </summary>
115         /// <param name="strclientid">ip:端口</param>
116         public void removeclient(string strclientid)
117         {
118             //要移除的用户名
119             string name = usersocket[strclientid];
120             //  要移除的在线管理的项
121             string onlinestr = strclientid + "---" + usersocket[strclientid] + @"---上线~\(≧▽≦)/~啦啦啦";
122 
123             //移除在线管理listclient 集合
124             if (listclient.items.contains(onlinestr))
125             {
126                 listclient.items.remove(onlinestr);
127             }
128             //断开socket连接
129             if (clientsocket.keys.contains(strclientid))
130             {
131                 clientsocket[strclientid].close();
132                 clientsocket.remove(strclientid);
133                 usersocket.remove(strclientid);
134             }
135             dgsendmsg(strclientid + "---" + name + @"---下线_" + datetime.now);
136         }
137         public void sendmsgtoclient(string msg)
138         {
139             //解析发来的数据
140 
141             string[] msgtxt = msg.split('|');
142 
143             //不可解析数据
144             if (msgtxt.length < 2)
145             {
146                 return;
147             }
148             //  解析收消息的用户名
149             string strto = msgtxt[1];
150             //获得当前发送的用户
151             var nowtouser = usersocket.where(w => w.value == strto).firstordefault();
152             if (nowtouser.key != null)
153             {
154                 byte[] buffer = system.text.encoding.utf8.getbytes(msg);
155                 socket conn = clientsocket[nowtouser.key];
156                 conn.send(buffer);
157             }
158 
159         }
160     }
161 }

 

  1 using system;
  2 using system.collections.generic;
  3 using system.drawing;
  4 using system.net;
  5 using system.net.sockets;
  6 using system.text;
  7 using system.threading;
  8 using system.windows.forms;
  9 
 10 namespace client
 11 {
 12     public partial class client : form
 13     {
 14         //客户端通信套接字
 15         private socket clientsocket;
 16         //新线程
 17         private thread thread;
 18         //当前登录的用户
 19         private string username = "";
 20         public client()
 21         {
 22             initializecomponent();
 23             //防止新线程调用主线程卡死
 24             checkforillegalcrossthreadcalls = false;
 25         }
 26 
 27         //通过ip地址与端口号与服务端建立链接       
 28         private void btntoserver_click(object sender, eventargs e)
 29         {
 30             //连接服务器前先选择用户
 31             if (cmbuser.text == null)
 32             {
 33                 messagebox.show("请选择登录用户");
 34                 return;
 35             }
 36             username = cmbuser.text.tostring();
 37             this.text = "当前用户:" + username;
 38             //登录后禁止切换用户
 39             cmbuser.enabled = false;
 40             //加载好友列表
 41             foreach (object item in cmbuser.items)
 42             {
 43                 if (item != cmbuser.selecteditem)
 44                 {
 45                     lbfriends.items.add(item);
 46                 }
 47             }
 48             //新建通信套接字
 49             clientsocket = new socket(addressfamily.internetwork, sockettype.stream, protocoltype.tcp);
 50             //这里的ip地址,端口号都是服务端绑定的相关数据。
 51             ipaddress ip = ipaddress.parse(txtip.text);
 52             var endpoint = new ipendpoint(ip, convert.toint32(txtport.text));
 53             try
 54             {
 55                 clientsocket.connect(endpoint); //链接有端口号与ip地址确定服务端.
 56                 //登录时给服务器发送登录消息
 57                 string str = username + "|" + " ";
 58                 byte[] buffer = encoding.utf8.getbytes(str);
 59                 clientsocket.send(buffer);
 60             }
 61             catch
 62             {
 63                 messagebox.show("与服务器连接失败");
 64                 lbfriends.items.clear();
 65             }
 66             //客户端在接受服务端发送过来的数据是通过socket 中的receive方法,
 67             //该方法会阻断线程,所以我们自己为该方法创建了一个线程
 68             thread = new thread(recemsg);
 69             thread.isbackground = true; //设置后台线程
 70             thread.start();
 71         }
 72 
 73         public void recemsg()
 74         {
 75             while (true)
 76             {
 77 
 78                 try
 79                 {
 80                     var buffer = new byte[1024 * 1024 * 2];
 81                     int datelength = clientsocket.receive(buffer); //接收服务端发送过来的数据
 82                     //把接收到的字节数组转成字符串显示在文本框中。
 83                     string receivemsg = encoding.utf8.getstring(buffer, 0, datelength);
 84                     string[] msgtxt = receivemsg.split('|');
 85                     string newstr = "      " + msgtxt[0] + ":我" + "\r\n" + "      " + msgtxt[2] + "           ____[" + datetime.now + "]" + "\r\n" + "\r\n";
 86                     showsmsg(newstr);
 87                 }
 88                 catch
 89                 {
 90 
 91                 }
 92             }
 93         }
 94 
 95         private void btnsend_click(object sender, eventargs e)
 96         {
 97             if (lbfriends.selecteditems.count != 1)
 98             {
 99                 messagebox.show("请选择好友");
100                 return;
101             }
102             string friend = lbfriends.selecteditem.tostring();
103             try
104             {
105                 //界面显示消息
106                 string newstr = "我" + ":" + friend + "\r\n" + txtmsg.text.trim() + "           ____[" + datetime.now +
107                                 "]" + "\r\n" + "\r\n";
108                 showsmsg(newstr);
109                 //发往服务器的消息     格式为 (发送者|接收者|信息)
110                 string str = username + "|" + friend + "|" + txtmsg.text.trim();
111                 //将消息转化为字节数据传输
112                 byte[] buffer = encoding.utf8.getbytes(str);
113                 clientsocket.send(buffer);
114                 txtmsg.text = "";
115             }
116             catch
117             {
118                 messagebox.show("与服务器连接失败");
119             }
120         }
121         //展示消息
122         private void showsmsg(string newstr)
123         {
124             txtchat.appendtext(newstr);
125         }
126         private void btncloseser_click(object sender, eventargs e)
127         {
128             clientsocket.close();
129         }
130     }
131 }

---------------------------------------------

udp打洞例子:

记住:在执行文件目录下有个ip.ini文件,内容是你的ip地址(假如是内网电脑就写内网ip,公网就写公网ip)

公共文件vjsdn.net.library:

 

  1 using system;
  2 using system.collections.generic;
  3 using system.text;
  4 using system.net;
  5 using system.net.sockets;
  6 using system.threading;
  7 using vjsdn.net.library;
  8 using system.windows.forms;
  9 using system.io;
 10 
 11 namespace vjsdn.net.library
 12 {
 13     /// <summary>
 14     /// 客户端业务类
 15     /// </summary>
 16     public class client : idisposable
 17     {
 18         //private const int max_retry_send_msg = 1; //打洞时连接次数,正常情况下一次就能成功
 19 
 20         private udpclient _client;//客户端监听器
 21         private ipendpoint _hostpoint; //主机ip
 22         private ipendpoint _remotepoint; //接收任何远程机器的数据
 23         private usercollection _userlist;//在线用户列表
 24         private thread _listenthread; //监听线程
 25         private string _localusername; //本地用户名
 26         //private bool _holeaccepted = false; //a->b,接收到b用户的确认消息
 27 
 28         private writeloghandle _onwritemessage;
 29         public writeloghandle onwritemessage
 30         {
 31             get { return _onwritemessage; }
 32             set { _onwritemessage = value; }
 33         }
 34 
 35         private userchangedhandle _userchangedhandle = null;
 36         public userchangedhandle onuserchanged
 37         {
 38             get { return _userchangedhandle; }
 39             set { _userchangedhandle = value; }
 40         }
 41 
 42         /// <summary>
 43         ///显示跟踪记录 
 44         /// </summary>
 45         /// <param name="log"></param>
 46         private void dowritelog(string log)
 47         {
 48             if (_onwritemessage != null)
 49                 (_onwritemessage.target as control).invoke(_onwritemessage, log);
 50         }
 51 
 52         /// <summary>
 53         /// 构造器
 54         /// </summary>
 55         /// <param name="serverip"></param>
 56         public client()
 57         {
 58             string serverip = this.getserverip();
 59             _remotepoint = new ipendpoint(ipaddress.any, 0); //任何与本地连接的用户ip地址。
 60             _hostpoint = new ipendpoint(ipaddress.parse(serverip), globals.server_port); //服务器地址
 61             _client = new udpclient();//不指定端口,系统自动分配
 62             _userlist = new usercollection();
 63             _listenthread = new thread(new threadstart(run));
 64         }
 65 
 66         /// <summary>
 67         /// 获取服务器ip,ini文件内设置
 68         /// </summary>
 69         /// <returns></returns>
 70         private string getserverip()
 71         {
 72             string file = application.startuppath + "\\ip.ini";
 73             string ip = file.readalltext(file);
 74             return ip.trim();
 75         }
 76 
 77         /// <summary>
 78         /// 启动客户端
 79         /// </summary>
 80         public void start()
 81         {
 82             if (this._listenthread.threadstate == threadstate.unstarted)
 83             {
 84                 this._listenthread.start();
 85             }
 86         }
 87 
 88         /// <summary>
 89         /// 客户登录
 90         /// </summary>
 91         public void login(string username, string password)
 92         {
 93             _localusername = username;
 94 
 95             // 发送登录消息到服务器
 96             c2s_loginmessage loginmsg = new c2s_loginmessage(username, password);
 97             this.sendmessage(loginmsg, _hostpoint);
 98         }
 99 
100         /// <summary>
101         /// 登出
102         /// </summary>
103         public void logout()
104         {
105             c2s_logoutmessage lgoutmsg = new c2s_logoutmessage(_localusername);
106             this.sendmessage(lgoutmsg, _hostpoint);
107 
108             this.dispose();
109             system.environment.exit(0);
110         }
111 
112         /// <summary>
113         /// 发送请求获取用户列表
114         /// </summary>
115         public void downloaduserlist()
116         {
117             c2s_getusersmessage getusermsg = new c2s_getusersmessage(_localusername);
118             this.sendmessage(getusermsg, _hostpoint);
119         }
120 
121         /// <summary>
122         /// 显示在线用户
123         /// </summary>
124         /// <param name="users"></param>
125         private void displayusers(usercollection users)
126         {
127             if (_userchangedhandle != null)
128                 (_userchangedhandle.target as control).invoke(_userchangedhandle, users);
129         }
130 
131         //运行线程
132         private void run()
133         {
134             try
135             {
136                 byte[] buffer;//接受数据用
137                 while (true)
138                 {
139                     buffer = _client.receive(ref _remotepoint);//_remotepoint变量返回当前连接的用户ip地址
140 
141                     object msgobj = objectserializer.deserialize(buffer);
142                     type msgtype = msgobj.gettype();
143                     dowritelog("接收到消息:" + msgtype.tostring() + " from:" + _remotepoint.tostring());
144 
145                     if (msgtype == typeof(s2c_userlistmessage))
146                     {
147                         // 更新用户列表
148                         s2c_userlistmessage usersmsg = (s2c_userlistmessage)msgobj;
149                         _userlist.clear();
150 
151                         foreach (user user in usersmsg.userlist)
152                             _userlist.add(user);
153 
154                         this.displayusers(_userlist);
155                     }
156                     else if (msgtype == typeof(s2c_useraction))
157                     {
158                         //用户动作,新用户登录/用户登出
159                         s2c_useraction msgaction = (s2c_useraction)msgobj;
160                         if (msgaction.action == useraction.login)
161                         {
162                             _userlist.add(msgaction.user);
163                             this.displayusers(_userlist);
164                         }
165                         else if (msgaction.action == useraction.logout)
166                         {
167                             user user = _userlist.find(msgaction.user.username);
168                             if (user != null) _userlist.remove(user);
169                             this.displayusers(_userlist);
170                         }
171                     }
172                     else if (msgtype == typeof(s2c_holepunchingmessage))
173                     {
174                         //接受到服务器的打洞命令
175                         s2c_holepunchingmessage msgholepunching = (s2c_holepunchingmessage)msgobj;
176 
177                         //nat-b的用户给nat-a的用户发送消息,此时udp包肯定会被nat-a丢弃,
178                         //因为nat-a上并没有a->nat-b的合法session, 但是现在nat-b上就建立了有b->nat-a的合法session了!                        
179                         p2p_holepunchingtestmessage msgtest = new p2p_holepunchingtestmessage(_localusername);
180                         this.sendmessage(msgtest, msgholepunching.remotepoint);
181                     }
182                     else if (msgtype == typeof(p2p_holepunchingtestmessage))
183                     {
184                         //udp打洞测试消息
185                         //_holeaccepted = true;
186                         p2p_holepunchingtestmessage msgtest = (p2p_holepunchingtestmessage)msgobj;
187                         updateconnection(msgtest.username, _remotepoint);
188 
189                         //发送确认消息
190                         p2p_holepunchingresponse response = new p2p_holepunchingresponse(_localusername);
191                         this.sendmessage(response, _remotepoint);
192                     }
193                     else if (msgtype == typeof(p2p_holepunchingresponse))
194                     {
195                         //_holeaccepted = true;//打洞成功
196                         p2p_holepunchingresponse msg = msgobj as p2p_holepunchingresponse;
197                         updateconnection(msg.username, _remotepoint);
198 
199                     }
200                     else if (msgtype == typeof(p2p_talkmessage))
201                     {
202                         //用户间对话消息
203                         p2p_talkmessage workmsg = (p2p_talkmessage)msgobj;
204                         dowritelog(workmsg.message);
205                     }
206                     else
207                     {
208                         dowritelog("收到未知消息!");
209                     }
210                 }
211             }
212             catch (exception ex) { dowritelog(ex.message); }
213         }
214 
215         private void updateconnection(string user, ipendpoint ep)
216         {
217             user remoteuser = _userlist.find(user);
218             if (remoteuser != null)
219             {
220                 remoteuser.netpoint = ep;//保存此次连接的ip及端口
221                 remoteuser.isconnected = true;
222                 dowritelog(string.format("您已经与{0}建立通信通道,ip:{1}!",
223                     remoteuser.username, remoteuser.netpoint.tostring()));
224                 this.displayusers(_userlist);
225             }
226         }
227 
228         #region idisposable 成员
229 
230         public void dispose()
231         {
232             try
233             {
234                 this._listenthread.abort();
235                 this._client.close();
236             }
237             catch
238             {
239 
240             }
241         }
242 
243         #endregion
244 
245         public void sendmessage(messagebase msg, user user)
246         {
247             this.sendmessage(msg, user.netpoint);
248         }
249 
250         public void sendmessage(messagebase msg, ipendpoint remoteip)
251         {
252             if (msg == null) return;
253             dowritelog("正在发送消息给->" + remoteip.tostring() + ",内容:" + msg.tostring());
254             byte[] buffer = objectserializer.serialize(msg);
255             _client.send(buffer, buffer.length, remoteip);
256             dowritelog("消息已发送.");
257         }
258 
259         /// <summary>
260         /// udp打洞过程
261         /// 假设a想连接b.首先a发送打洞消息给server,让server告诉b有人想与你建立通话通道,server将a的ip信息转发给b
262         /// b收到命令后向a发一个udp包,此时b的nat会建立一个与a通讯的session. 然后a再次向b发送udp包b就能收到了
263         /// </summary>
264         public void holepunching(user user)
265         {
266             //a:自己; b:参数user
267             //a发送打洞消息给服务器,请求与b打洞
268             c2s_holepunchingrequestmessage msg = new c2s_holepunchingrequestmessage(_localusername, user.username);
269             this.sendmessage(msg, _hostpoint);
270 
271             thread.sleep(2000);//等待对方发送udp包并建立session
272 
273             //再向对方发送确认消息,如果对方收到会发送一个p2p_holepunchingresponse确认消息,此时打洞成功
274             p2p_holepunchingtestmessage confirmmessage = new p2p_holepunchingtestmessage(_localusername);
275             this.sendmessage(confirmmessage, user);
276         }
277     }
278 
279 }

 

  1 using system;
  2 using system.io;
  3 using system.runtime.serialization.formatters.binary;
  4 using system.net;
  5 using system.collections;
  6 
  7 namespace vjsdn.net.library
  8 {
  9     /// <summary>
 10     /// 显示跟踪消息的事件委托
 11     /// </summary>
 12     public delegate void writeloghandle(string msg);
 13 
 14     /// <summary>
 15     /// 刷新在线用户的事件委托
 16     /// </summary>    
 17     public delegate void userchangedhandle(usercollection users);
 18 
 19     public class globals
 20     {
 21         /// <summary>
 22         /// 服务器侦听端口
 23         /// </summary>
 24         public const int server_port = 21134;
 25 
 26         /// <summary>
 27         /// 本地侦听端口
 28         /// </summary>
 29         public const int local_port = 19786;
 30     }
 31 
 32     /// <summary>
 33     /// user 的摘要说明。
 34     /// </summary>
 35     [serializable]
 36     public class user
 37     {
 38         protected string _username;
 39         protected ipendpoint _netpoint;
 40         protected bool _conntected;
 41 
 42         public user(string username, ipendpoint netpoint)
 43         {
 44             this._username = username;
 45             this._netpoint = netpoint;
 46         }
 47 
 48         public string username
 49         {
 50             get { return _username; }
 51         }
 52 
 53         public ipendpoint netpoint
 54         {
 55             get { return _netpoint; }
 56             set { _netpoint = value; }
 57         }
 58 
 59         public bool isconnected //打洞标记
 60         {
 61             get { return _conntected; }
 62             set { _conntected = value; }
 63         }
 64 
 65         public string fullname { get { return this.tostring(); } }
 66 
 67         public override string tostring()
 68         {
 69             return _username + "- [" + _netpoint.address.tostring() + ":" + _netpoint.port.tostring() + "] " + (_conntected ? "y" : "n");
 70         }
 71     }
 72 
 73     /// <summary>
 74     /// 在线用户列表
 75     /// </summary>
 76     [serializable]
 77     public class usercollection : collectionbase
 78     {
 79         public void add(user user)
 80         {
 81             innerlist.add(user);
 82         }
 83 
 84         public void remove(user user)
 85         {
 86             innerlist.remove(user);
 87         }
 88 
 89         public user this[int index]
 90         {
 91             get { return (user)innerlist[index]; }
 92         }
 93 
 94         public user find(string username)
 95         {
 96             foreach (user user in this)
 97             {
 98                 if (string.compare(username, user.username, true) == 0)
 99                 {
100                     return user;
101                 }
102             }
103             return null;
104         }
105     }
106 
107     /// <summary>
108     /// 序列化反序列化对象
109     /// </summary>
110     public class objectserializer
111     {
112         public static byte[] serialize(object obj)
113         {
114             binaryformatter binaryf = new binaryformatter();
115             memorystream ms = new memorystream(1024 * 10);
116             binaryf.serialize(ms, obj);
117             ms.seek(0, seekorigin.begin);
118             byte[] buffer = new byte[(int)ms.length];
119             ms.read(buffer, 0, buffer.length);
120             ms.close();
121             return buffer;
122         }
123 
124         public static object deserialize(byte[] buffer)
125         {
126             binaryformatter binaryf = new binaryformatter();
127             memorystream ms = new memorystream(buffer, 0, buffer.length, false);
128             object obj = binaryf.deserialize(ms);
129             ms.close();
130             return obj;
131         }
132     }
133 
134 
135 }
  1 using system;
  2 using system.collections.generic;
  3 using system.text;
  4 
  5 namespace vjsdn.net.library
  6 {
  7 
  8     /// <summary>
  9     /// 消息基类,抽象类
 10     /// </summary>
 11     [serializable]
 12     public abstract class messagebase
 13     {
 14         //消息基类
 15     }
 16 
 17 
 18     #region 客户端发送到服务器的消息
 19 
 20     /// <summary>
 21     /// 客户端发送到服务器的消息基类
 22     /// </summary>
 23     [serializable]
 24     public abstract class c2s_messagebase : messagebase
 25     {
 26         private string _fromusername;
 27 
 28         protected c2s_messagebase(string fromusername)
 29         {
 30             _fromusername = fromusername;
 31         }
 32 
 33         public string fromusername
 34         {
 35             get { return _fromusername; }
 36         }
 37     }
 38 
 39     /// <summary>
 40     /// 用户登录消息
 41     /// </summary>
 42     [serializable]
 43     public class c2s_loginmessage : c2s_messagebase
 44     {
 45         private string _password;
 46 
 47         public c2s_loginmessage(string username, string password)
 48             : base(username)
 49         {
 50             this._password = password;
 51         }
 52 
 53         public string password
 54         {
 55             get { return _password; }
 56         }
 57     }
 58 
 59     /// <summary>
 60     /// 用户登出消息
 61     /// </summary>
 62     [serializable]
 63     public class c2s_logoutmessage : c2s_messagebase
 64     {
 65 
 66         public c2s_logoutmessage(string username)
 67             : base(username)
 68         { }
 69     }
 70 
 71     /// <summary>
 72     /// 请求用户列表消息
 73     /// </summary>
 74     [serializable]
 75     public class c2s_getusersmessage : c2s_messagebase
 76     {
 77         public c2s_getusersmessage(string username)
 78             : base(username)
 79         { }
 80     }
 81 
 82     /// <summary>
 83     /// 请求purch hole消息
 84     /// </summary>
 85     [serializable]
 86     public class c2s_holepunchingrequestmessage : c2s_messagebase
 87     {
 88         protected string tousername;
 89 
 90         public c2s_holepunchingrequestmessage(string fromusername, string tousername)
 91             : base(fromusername)
 92         {
 93             this.tousername = tousername;
 94         }
 95 
 96         public string tousername
 97         {
 98             get { return this.tousername; }
 99         }
100     }
101 
102     #endregion
103 
104     #region 点对点消息
105 
106     /// <summary>
107     /// 点对点消息基类
108     /// </summary>
109     [serializable]
110     public abstract class p2p_messagebase : messagebase
111     {
112         //
113     }
114 
115     /// <summary>
116     /// 聊天消息
117     /// </summary>
118     [serializable]
119     public class p2p_talkmessage : p2p_messagebase
120     {
121         private string message;
122 
123         public p2p_talkmessage(string msg)
124         {
125             message = msg;
126         }
127 
128         public string message
129         {
130             get { return message; }
131         }
132     }
133 
134     /// <summary>
135     /// udp打洞测试消息
136     /// </summary>
137     [serializable]
138     public class p2p_holepunchingtestmessage : p2p_messagebase
139     {
140         private string _username;
141 
142         public p2p_holepunchingtestmessage(string username)
143         {
144             _username = username;
145         }
146 
147         public string username
148         {
149             get { return _username; }
150         }
151     }
152 
153     /// <summary>
154     /// 收到消息的回复确认
155     /// 如a与b想建立通话通道,些命令由b发出确认打洞成功
156     /// </summary>
157     [serializable]
158     public class p2p_holepunchingresponse : p2p_messagebase
159     {
160         private string _username;
161 
162         public p2p_holepunchingresponse(string username)
163         {
164             _username = username;
165         }
166 
167         public string username
168         {
169             get { return _username; }
170         }
171     }
172 
173     #endregion
174 
175     #region 服务器发送到客户端消息
176 
177     /// <summary>
178     /// 服务器发送到客户端消息基类
179     /// </summary>
180     [serializable]
181     public abstract class s2c_messagebase : messagebase
182     {
183     }
184 
185     /// <summary>
186     /// 请求用户列表应答消息
187     /// </summary>
188     [serializable]
189     public class s2c_userlistmessage : s2c_messagebase
190     {
191         private usercollection userlist;
192 
193         public s2c_userlistmessage(usercollection users)
194         {
195             this.userlist = users;
196         }
197 
198         public usercollection userlist
199         {
200             get { return userlist; }
201         }
202     }
203 
204     /// <summary>
205     /// 转发请求purch hole消息
206     /// </summary>
207     [serializable]
208     public class s2c_holepunchingmessage : s2c_messagebase
209     {
210         protected system.net.ipendpoint _remotepoint;
211 
212         public s2c_holepunchingmessage(system.net.ipendpoint point)
213         {
214             this._remotepoint = point;
215         }
216 
217         public system.net.ipendpoint remotepoint
218         {
219             get { return _remotepoint; }
220         }
221     }
222 
223     /// <summary>
224     /// 服务器通知所有在线用户,
225     /// </summary>
226     [serializable]
227     public class s2c_useraction : s2c_messagebase
228     {
229         protected user _user;
230         protected useraction _action;
231 
232         public s2c_useraction(user user, useraction action)
233         {
234             _user = user;
235             _action = action;
236         }
237 
238         public user user
239         {
240             get { return _user; }
241         }
242 
243         public useraction action
244         {
245             get { return _action; }
246         }
247     }
248 
249     #endregion
250 
251     /// <summary>
252     /// 用户动作
253     /// </summary>
254     public enum useraction
255     {
256         login,
257         logout
258     }
259 }
  1 using system;
  2 using system.collections.generic;
  3 using system.text;
  4 using system.net;
  5 using system.net.sockets;
  6 using system.threading;
  7 using vjsdn.net.library;
  8 using system.windows.forms;
  9 
 10 namespace vjsdn.net.library
 11 {
 12     /// <summary>
 13     /// 服务器端业务类
 14     /// </summary>
 15     public class server
 16     {
 17         private udpclient _server; //服务器端消息监听器
 18         private usercollection _userlist; //在线用户列表
 19         private thread _serverthread; 
 20         private ipendpoint _remotepoint; //远程用户请求的ip地址及端口
 21 
 22         private writeloghandle _writeloghandle = null;
 23         private userchangedhandle _userchangedhandle = null;
 24 
 25         /// <summary>
 26         /// 显示跟踪消息
 27         /// </summary>
 28         public writeloghandle onwritelog
 29         {
 30             get { return _writeloghandle; }
 31             set { _writeloghandle = value; }
 32         }
 33 
 34         /// <summary>
 35         /// 当用户登入/登出时触发此事件
 36         /// </summary>
 37         public userchangedhandle onuserchanged
 38         {
 39             get { return _userchangedhandle; }
 40             set { _userchangedhandle = value; }
 41         }
 42 
 43         /// <summary>
 44         /// 构造器
 45         /// </summary>
 46         public server()
 47         {
 48             _userlist = new usercollection();
 49             _remotepoint = new ipendpoint(ipaddress.any, 0);
 50             _serverthread = new thread(new threadstart(run));
 51         }
 52 
 53         /// <summary>
 54         ///显示跟踪记录 
 55         /// </summary>
 56         /// <param name="log"></param>
 57         private void dowritelog(string log)
 58         {
 59             if (_writeloghandle != null)
 60                 (_writeloghandle.target as system.windows.forms.control).invoke(_writeloghandle, log);
 61         }
 62 
 63         /// <summary>
 64         /// 刷新用户列表
 65         /// </summary>
 66         /// <param name="list">用户列表</param>
 67         private void douserchanged(usercollection list)
 68         {
 69             if (_userchangedhandle != null)
 70                 (_userchangedhandle.target as control).invoke(_userchangedhandle, list);
 71         }
 72 
 73         /// <summary>
 74         /// 开始启动线程
 75         /// </summary>
 76         public void start()
 77         {
 78             try
 79             {
 80                 _server = new udpclient(globals.server_port);
 81                 _serverthread.start();
 82                 dowritelog("服务器已经启动,监听端口:" + globals.server_port.tostring() + ",等待客户连接...");
 83             }
 84             catch (exception ex)
 85             {
 86                 dowritelog("启动服务器发生错误: " + ex.message);
 87                 throw ex;
 88             }
 89         }
 90 
 91         /// <summary>
 92         /// 停止线程
 93         /// </summary>
 94         public void stop()
 95         {
 96             dowritelog("停止服务器...");
 97             try
 98             {
 99                 _serverthread.abort();
100                 _server.close();
101                 dowritelog("服务器已停止.");
102             }
103             catch (exception ex)
104             {
105                 dowritelog("停止服务器发生错误: " + ex.message);
106                 throw ex;
107             }
108         }
109 
110         //线程主方法
111         private void run()
112         {
113             byte[] msgbuffer = null;
114 
115             while (true)
116             {
117                 msgbuffer = _server.receive(ref _remotepoint); //接受消息
118                 try
119                 {
120                     //将消息转换为对象
121                     object msgobject = objectserializer.deserialize(msgbuffer);
122                     if (msgobject == null) continue;
123 
124                     type msgtype = msgobject.gettype();
125                     dowritelog("接收到消息:" + msgtype.tostring());
126                     dowritelog("from:" + _remotepoint.tostring());
127 
128                     //新用户登录
129                     if (msgtype == typeof(c2s_loginmessage))
130                     {
131                         c2s_loginmessage lginmsg = (c2s_loginmessage)msgobject;
132                         dowritelog(string.format("用户'{0}'已登录!", lginmsg.fromusername));
133 
134                         // 添加用户到列表
135                         ipendpoint userendpoint = new ipendpoint(_remotepoint.address, _remotepoint.port);
136                         user user = new user(lginmsg.fromusername, userendpoint);
137                         _userlist.add(user);
138 
139                         this.douserchanged(_userlist);
140 
141                         //通知所有人,有新用户登录
142                         s2c_useraction msgnewuser = new s2c_useraction(user, useraction.login);
143                         foreach (user u in _userlist)
144                         {
145                             if (u.username == user.username) //如果是自己,发送所有在线用户列表
146                                 this.sendmessage(new s2c_userlistmessage(_userlist), u.netpoint);
147                             else
148                                 this.sendmessage(msgnewuser, u.netpoint);
149                         }
150                     }
151                     else if (msgtype == typeof(c2s_logoutmessage))
152                     {
153                         c2s_logoutmessage lgoutmsg = (c2s_logoutmessage)msgobject;
154                         dowritelog(string.format("用户'{0}'已登出!", lgoutmsg.fromusername));
155 
156                         // 从列表中删除用户
157                         user logoutuser = _userlist.find(lgoutmsg.fromusername);
158                         if (logoutuser != null) _userlist.remove(logoutuser);
159 
160                         this.douserchanged(_userlist);
161 
162                         //通知所有人,有用户登出
163                         s2c_useraction msgnewuser = new s2c_useraction(logoutuser, useraction.logout);
164                         foreach (user u in _userlist)
165                             this.sendmessage(msgnewuser, u.netpoint);
166                     }
167 
168                     else if (msgtype == typeof(c2s_holepunchingrequestmessage))
169                     {
170                         //接收到a给b打洞的消息,打洞请求,由客户端发送给服务器端
171                         c2s_holepunchingrequestmessage msgholereq = (c2s_holepunchingrequestmessage)msgobject;
172                         
173                         user usera = _userlist.find(msgholereq.fromusername);
174                         user userb = _userlist.find(msgholereq.tousername);
175 
176                         // 发送打洞(punching hole)消息
177                         dowritelog(string.format("用户:[{0} ip:{1}]想与[{2} ip:{3}]建立对话通道.",
178                           usera.username, usera.netpoint.tostring(),
179                           userb.username, userb.netpoint.tostring()));
180 
181                         //由server发送消息给b,将a的ip的ip地址信息告诉b,然后由b发送一个测试消息给a.
182                         s2c_holepunchingmessage msgholepunching = new s2c_holepunchingmessage(_remotepoint);
183                         this.sendmessage(msgholepunching, userb.netpoint); //server->b
184                     }
185                     else if (msgtype == typeof(c2s_getusersmessage))
186                     {
187                         // 发送当前用户信息
188                         s2c_userlistmessage srvresmsg = new s2c_userlistmessage(_userlist);
189                         this.sendmessage(srvresmsg, _remotepoint);
190                     }
191                 }
192                 catch (exception ex) { dowritelog(ex.message); }
193             }
194         }
195         /// <summary>
196         /// 发送消息
197         /// </summary>
198         public void sendmessage(messagebase msg, ipendpoint remoteip)
199         {
200             dowritelog("正在发送消息:" + msg.tostring());
201             if (msg == null) return;
202             byte[] buffer = objectserializer.serialize(msg);
203             _server.send(buffer, buffer.length, remoteip);
204             dowritelog("消息已发送.");
205         }
206     }
207 }

server:(vjsdn.net.server)

 

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.text;
 7 using system.windows.forms;
 8 using vjsdn.net.library;
 9 
10 namespace p2pserver
11 {
12     public partial class frmserver : form
13     {
14         private server _server;
15 
16         public frmserver()
17         {
18             initializecomponent();
19         }
20 
21         private void button1_click(object sender, eventargs e)
22         {
23             _server = new server();
24             _server.onwritelog += new writeloghandle(server_onwritelog);
25             _server.onuserchanged += new userchangedhandle(onuserchanged);
26             try
27             {
28                 _server.start();
29             }
30             catch (exception ex)
31             {
32                 messagebox.show(ex.message);
33             }
34         }
35 
36         //刷新用户列表
37         private void onuserchanged(usercollection users)
38         {
39             listbox2.displaymember = "fullname";
40             listbox2.datasource = null;
41             listbox2.datasource = users;
42         }
43 
44         //显示跟踪消息
45         public void server_onwritelog(string msg)
46         {
47             listbox1.items.add(msg);
48             listbox1.selectedindex = listbox1.items.count - 1;
49         }
50 
51         private void button2_click(object sender, eventargs e)
52         {
53             application.exit();
54         }
55 
56         private void frmserver_formclosing(object sender, formclosingeventargs e)
57         {
58             if (_server != null)
59                 _server.stop();
60         }
61 
62         private void button3_click(object sender, eventargs e)
63         {
64             //发送消息给所有在线用户
65             p2p_talkmessage msg = new p2p_talkmessage(textbox1.text);
66             foreach (object o in listbox2.items)
67             {
68                 user user = o as user;
69                 _server.sendmessage(msg, user.netpoint);
70             }
71         }
72 
73         private void button6_click(object sender, eventargs e)
74         {
75             listbox1.items.clear();
76         }
77     }
78 }

client:(vjsdn.net.client) 

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.text;
 7 using system.windows.forms;
 8 using system.net;
 9 using system.net.sockets;
10 using vjsdn.net.library;
11 
12 namespace vjsdn.net
13 {
14     public partial class frmclient : form
15     {
16         private client _client;
17 
18         public frmclient()
19         {
20             initializecomponent();
21         }
22 
23         private void frmclient_load(object sender, eventargs e)
24         {
25             _client = new client();
26             _client.onwritemessage = this.writelog;
27             _client.onuserchanged = this.onuserchanged;
28         }
29 
30         private void button1_click(object sender, eventargs e)
31         {
32             _client.login(textbox2.text, "");
33             _client.start();
34         }
35 
36         private void writelog(string msg)
37         {
38             listbox2.items.add(msg);
39             listbox2.selectedindex = listbox2.items.count - 1;
40         }
41 
42         private void button4_click(object sender, eventargs e)
43         {
44             this.close();
45         }
46 
47         private void button3_click(object sender, eventargs e)
48         {
49             if (_client != null)
50             {
51                 user user = listbox1.selecteditem as user;
52                 _client.holepunching(user);
53             }
54         }
55 
56         private void button2_click(object sender, eventargs e)
57         {
58             if (_client != null) _client.downloaduserlist();
59         }
60 
61         private void frmclient_formclosing(object sender, formclosingeventargs e)
62         {
63             if (_client != null) _client.logout();
64         }
65 
66         private void onuserchanged(usercollection users)
67         {
68             listbox1.displaymember = "fullname";
69             listbox1.datasource = null;
70             listbox1.datasource = users;
71         }
72 
73         private void button5_click(object sender, eventargs e)
74         {
75             p2p_talkmessage msg = new p2p_talkmessage(textbox1.text);
76             user user = listbox1.selecteditem as user;
77             _client.sendmessage(msg, user);
78         }
79 
80         private void button6_click(object sender, eventargs e)
81         {
82             listbox2.items.clear();
83         }
84     }
85 }

 ---------------------------

项目:局域网五子棋、远程操控、

 

  

 数据库

sql server: 

sql server 一共有4个系统数据库:
master:记录sql server系统的所有系统级信息,例如:登陆账户信息、链接服务器和系统配置设置、记录其他所有数据库的存在、数据文件的位置、sql server的初始化信息等。如果master数据库不可用、则无法启动sql server
msdb:用于sql server代理计划警报和作业。数据库定时执行某些操作、数据库邮件等。
model:用作sql server实例上创建的所有数据库的模板。对model数据库进行的修改(如数据库大小、排序规则、恢复模式和其他数据库选项)将应用于以后创建的所有数据库。在model数据库中创建一张表,则以后每次创建数据库的时候都会有默认的一张同样的表。
tempdb:一个工作空间,用于保存临时对象或中间结果集。一个全局资源,可供连接到sql
server实例的所有用户使用。每次启动sql server是都会重新创建tempdb

--创建一个数据库
create database mydatabase;--默认的
--删除数据库
drop database mydatabase;
--------------------------------------------------------------------
create database bblovedd
on primary
(
 --配置主数据文件的选项
 name='bblovedd',--主数据文件的逻辑名称 建议和数据库名字一样
 filename='d:\bblovedd.mdf',--主数据文件的诗句保存路径
 size=5mb,
 maxsize=150mb,
 filegrowth=20%
)
log on --日志文件
(
 --配置日志文件的选项
 name='bblovedd_log',--主数据文件的逻辑名称
 filename='d:\bblovedd_log.ldf',--日志文件的实际保存路径
 size=5mb,
 filegrowth=5mb

 )

  

这时要是想要在d盘删除这两个文件但是删除不了,是因为文件被占用了,下面会讲解分离之后删除。

-------------------------------------------------------------------------------------------

--创建数据库表

use bblovedd  --将代码环境切换到bblovedd

 

create table bblovedd --表名随便写

(

id int identity(1,1) primary key,--设置主键

name nvarchar(50) not null --数据类型,输入汉字的要用n

)

 

--删除表
use bblovedd
drop table bblovedd

--创建一个员工表
--员工表:员工id,身份证号,姓名,性别,入职日期,年龄,地址,电话,所属部门,email
use bblovedd
create table bblovedd
(
    bb_id int identity(1,1) primary key,
    bb_idcard varchar(18) not null,
    bb_name nvarchar(50) null,
    bb_cender bit not null,
    bb_joindata datetime,
    bb_age int,
    bb_address nvarchar(300),
    bb_phone varchar(100),
    dd_id int not null,
    bb_email varchar(100)
) 
insert into 数据插入
insert into 表明(列名,列名...) values(值1,值2...)
insert 语句可以省略表名后的列名,就是全部列都要添加数据
自动编号列不需要手动插入。
主键不能有重复值
插入另一个表的数据(类型要匹配才行):
insert into 表名(列) select 列 from 表
n前缀:字符串的前面加n   n‘字符串’
uuse bblovedd 
create table bbdd 
(
    id int identity(1,1) primary key,
    name nvarchar(50) not null 
)
insert into bbdd(name) values(n'毕小帅')
insert into bbdd(name) values(n'小丹丹')
update 数据更新
--update 表名set 列=新值,列=新值,...where 条件
--update语句如果不加where就是表示表中的所有的数据都进行更改
update bbdd set name = '丹丹' where name = '小丹丹'
--where 中可以使用的其他逻辑运算符:(||)or、(&&)and、(!)not、<、
-->、>=、<=、<>(或!=)等

--删除数据语句
--delete from 表名where...
--delete语句如果不加where条件,表示将表中所有数据都删除,加where条件后,
--会按照where条件进行删除
insert into bbdd(name) values(n'小丹丹')--先添加一行数据
delete from bbdd where name='小丹丹'
--delete from bbdd --删除所有数据不会恢复自动编号
--另一种删除全部数据的
truncate table bbdd
--如果确实要删除表中全部数据,那么建议使用truncate
--truncate特点:
    --1.truncate语句不能跟where条件(无法根据条件来删除,只能全部删除数据)
    --2.同时自动编号恢复到初始值。
    --3.使用truncate删除表中所有数据要比delete效率高的多。    

--数据库约束是为了保证数据的完整性(正确性)而实现的一套机制
--非空约束
--主键约束(pk)primary key 唯一切不能为空
--唯一约束(uq)unique 唯一,允许为空,但只能出现一次
--默认约束(df)default 默认值
--检查约束(ck)check 范围以及格式限制
--外键约束(fk)foreign key 表关系
--增加外键约束时,设置级联更新、级联删除

alter table 表名 drop column 列名 -- 删除一列
alter table 表名 add 列名 nvarchar(100)
alter table 表名 alter column 列名 varchar(200)--修改列属性
alter table 表名 add constraint 随意起个约束名-pk_employees_列名 primary key(列名)--添加主键约束
alter table 表名 alter column 列名 varchar(50) not null--添加非空约束
alter table 表名 add constraint 随意起个约束名-uq_employees_列名 unique(列名)--添加唯一约束
alter table 表名 add constraint 随意起个约束名-df_employees_列名 default('不男不女') for 列名--添加默认约束
alter table 表名 add constraint 随意起个约束名-ck_employees_列名 check(列名='男' 列名='女')--添加检查约束
alter table 表名 add constraint 随意起个约束名-pk_employees_列名 primary key(列名)--设置主键列
alter table 表名 add constraint 随意起个约束名-pk_employees_列名 foreign key(当前表的列明) references 另一个表表名(另个表的主键列)--增加外键约束
alter table 表名 drop constraint 约束名 --删除约束
--创建表时直接加约束:
create  table 员工表
(
    id int identity(1,1) primary key,
    name varchar(50) not null unique check(len(name)>2),
    gender char(2) default('男'),
    age int check(age>0 and age<100),
    email varchar(100) unique,
    address varchar(500) not null,
    bldid int foreign key references bld(id) on delete cascade --外检约束级联
)
create table bld
(
    id int identity(1,1) primary key,
    name varchar(50) not null unique
) 
--select查询 
--简单的数据检索:select * from 表名
--指检索需要的列:select 列名可以查看多个列from 表名
--列别名:select name as 姓名,select age as 年龄from 表名
    --还可以这样其别名:select 姓名=name ,select 年龄=age  from 表名
--使用where检索符合条件的数据:select name from 表名where sex='男'
--检索不与任何表关联的数据:select 1+1;select getdate();--直接显示出和当前时间-- 这样就是select也可以不与from一起使用
--distinct关键字,针对已经查询出的结果然后去除重复
--select distinct * from 表名

--order by 列名
select *from 表名 order by 列名 desc --降序排序
select *from 表名 order by 列名 asc --升序排序
select *from 表名 order by 表名 --默认就是升序排序

select top 3 * from 表名 order by 列名 desc --查询前
select top 3 * from 表名 order by 列名 asc --查询后
select top 30 percent * from 表名 order by 列名 desc --查询前%
select top 30 percent * from 表名 order by 列名 asc --查询后%
--聚合函数聚合函数是聚合行中的数据
--常用的几个聚合函数:
    --max(最大值)、min(最小值)、avg(平均值)、sum(和)、count(数量:记录的条数)
--聚合函数对null不计算
--如果一行的数据都是null,count(*)包含对空值行、重复行的统计
模糊查询
--模糊查询:
--通配符:_   %   []   ^

--  _ 表示任意的单个字符
select * from 表名 where name like '毕_'  --姓毕的两个字名字
select * from 表名 where name like '毕__'  --姓毕的三个字名字

-- []筛选范围匹配一个
select *from 表名 where 列名 like '毕[0-9]丹'--毕丹、毕丹.....
select *from 表名 where 列名 like '毕[毕a-z]'--毕a丹、毕b丹.....
select *from 表名 where 列名 like '毕[a-z0-9]丹'--毕a1丹、毕a2丹、毕b2丹.....

-- %
select *from 表名 where 列名 like '毕%' --头个一个字是毕的全部查询出来

-- ^非除了sqlserver 其他数据库就是not like
select *from 表名 where 列名 like '毕[^0-9]丹'--只要毕丹之间不是-9的数字都会查询出来

--转义符
select * from 表名 where 列名 like '%/[/]%' escape '/'--数据中带有[]的都会查询出来

--replace 替换关键字
update bbdd set name=replace(name ,'毕毕','bb')--将表中name列内数据为毕毕全部替换成bb

--null
--null值无法使用=或<>来进行比较
select * from 表名 where 列名=null --这是错误的
select * from 表名 where 列名<>null --列名不等于null 这也是错误的

--正确写法:
    select *from 表名 where 列名 is null
    select *from 表名 where 列名 is not null
--多列排序
select *from 表名 order by 列名 desc,列名 desc
分组:
--在使用select查询的时候,有时需要对数据进行分组汇总(即:将现有的数据
--按照某列来汇总统计),这是就需要用到group by语句。
--select语句中可以使用group by子句将行划分成较小的组,然后使用聚组函数返回每一个组的汇总信息。
--分组一般都和聚合函数连用
--group by子句必须放在where语句的之后,group by与order by都是对筛选后的数据进行处理,而where是用来筛选数据的。
--没有出现在group by子句中的列是不能放到select语句后的列名列表中的(聚合函数中除外)
--例子:
    --错误:select id, name from bbdd group by name
    --正确:select id,count(name)from bbdd group by id
    
--对分组以后的数据进行筛选使用having
--having与where都是对数据进行筛选,where是对分组前的每一行数据进行筛选
--而having是对分组后的每一组数据进行筛选
--select 
    --id as id,
    --人数=count(*)
--from bbdd
--group by id
--having count(*)>3

--having语句(对组的筛选,哪些组显示哪些组不显示)
--1.对表中的数据分组后,会得到一个分组的结果集,如何对该结果集在进行筛选?-->having
--2.注意having中不能使用未参与分组的列,having不能替代where。作用不一样,having是对组进行过滤。
    --where是对每天记录进行过滤的。
--3.having是group by的条件对分组后的数据进行筛选(与where类似,都是筛选,只不过having是用来筛选分组后的组的。)
--4.在where中不能使用聚合函数,必须使用having,having要位于group by之后。
--5.having的使用几乎是与where一样的,也可以用in。
上下是一起的
select 
    商品名称
    sum(销售数量) as 销售数量
from 超市
group by 商品名称
order by 销售数量 desc
分组要和聚合函数一起

上下
select语句的处理顺序:
1.from
2.on
3.join
4.where
5.group by 
6.with cube 或 with rollup
7.having 
8.select
9.distinct
10.order by
11.top

类型转换:
cast(表达式 as 数据类型)
convert(数据类型 , 表达式)
select 100.0 + cast('1000' as int)
select 100.0 + convert(int , '1000') --两次都是一样的,将字符串'1000'转换成了int型在于.0相加

select '类型转字符串:' + convert(char(1),2)--整形转换成字符

print convert(varchar(10), getdate(), 120)--转换日期格式,是一种格式
联合结果集union(集合运算符)
1.集合运算符是对两个集合操作的,两个集合必须具有相同的列数,列具有相同的数据类型(至少能隐式转换的),
最终输出的集合的列名由第一个集合的列名来确定。(可以用来连接多个结果)
2.联合(union)与连接(join)不一样
3.例子:
    select id,name from bbdd
    union
    select id,name from bld
4.联合:将多个结果集合并成一个结果集.union(去除重复,相当于默认应用了distinct),union all
5.常见应用:底部汇总。使用union all 不去除重复
    例子:统计每种商品的销售总价,并且在底部做汇总
    select 
        商品名称
        销售总价 = sum(销售价格*销售数量)
    from 超市
    group by 商品名称
    union all
    select '总销售价格',sum(销售价格*销售数量)from 超市
    order by 销售总价 asc
6.union all 向表中插入多条数据
 insert into bld
 select '毕毕love丹丹'
 union all
 select '毕毕love丹丹'
 union all
 select '毕毕love丹丹'
 --向表中插入了三条数据,假如不加all那就是一条了,union去除重复

备份:
备份表,但是约束没有拷贝过去,前提表不存在
 select * into 备份表bbdd from bbdd    
 
 拷贝表结构,不拷贝数据,前提表不存在
 select top 0 * into 表结构bbdd from bbdd 

假如表已经存在了,还要备份:
insert into 存在的备份表bbdd select * from bbdd --!!!!提前要有这个表!!!
--常用的字符串函数:
--1.len() 计算字符的个数
print len('毕毕love丹丹')
--2.datalength()返回锁占用的字节的个数,这个不是字符串函数
print datalength('毕毕love丹丹')---12
print datalength(n'毕毕love丹丹')---16
--3.转换大小写
print upper('毕毕love丹丹')--转换大写
print lower('毕毕love丹丹')--转换小写
--4.去掉两端空格
print '1111'+'    毕毕love丹丹   '+'1111'
print '1111'+ltrim('    毕毕love丹丹   ')+'1111'--去掉左边空格
print '1111'+rtrim('    毕毕love丹丹   ')+'1111'--去掉右边空格
print '1111'+rtrim(ltrim('    毕毕love丹丹   '))+'1111'--去掉两边空格
--5.字符串截取
    --left()左边截取
    print left('毕毕love丹丹',2)--从左边截取两个
    --right()右边截取    
    print right('毕毕love丹丹',2)--从右边截取两个

--时间:
--查询入职一年或以上的员工信息
select 
*
from 员工表   --dateadd() 是增加时间
where dateadd(year,1,入职日期)<=getdate() --入职日期加上年和当前时间对比

--datediff()计算两个日期的差
select datediff(year,'2000-01-01',getdate())
select datediff(month,'2000-01-01',getdate())
select datediff(day,'2000-01-01',getdate())
select datediff(hour,'2000-01-01',getdate())
select datediff(minute,'2000-01-01',getdate())
select datediff(second,'2000-01-01',getdate())

--返回日期的某部分,字符串表示形式.datepart()是数字表示形式
print datename(year,getdate())--字符串表示形式

--datepart()数字表示形式
print datepart(year,getdate())
print datepart(month,getdate())
print datepart(day,getdate())

--打印时间
print getdate()
print sysdatetime()--中国方式

--计算工龄
select 
    工龄=datediff(year,入职日期,getdate())
    count(*) as 人数
from 员工表
group by datediff(year,入职日期,getdate())

 ado.net:

 

1.ado.net组成:

数据提供程序(常用类)

connection,用来连接数据库

command,用来执行sql语句

datareader只读、只进的结果集,一条一条读取数据(streamreaderxmlreader微软的类库中这些reader的使用方式都差不多)

dataadapter,一个封装了上面3个对象的对象。

 

数据集(dataset),临时数据库。

断开式数据操作

 

2.连接数据库的步骤(推荐集成连接方式)

 

3.插入

4.删除

 

5.更新

 

6.查询表记录数量

 

7.datareader1

 

7.datareader2

 

7.datareader3

7.datareader4

7.datareader5

7.datareader6

 

8.dbnull

另一个文件

1.null

2.dgv数据绑定(反射只认属性不认字段)

3.插入

3.1

4.行获取焦点事件

5.保存数据1

 

5.保存数据2

 

6.删除

7.插入后返回编号

---------------------------------------------------------

sql注入攻击:

1.验证登陆

2.用户名密码判断

3.漏洞

-------------------------------------------------------------------------------

带参数:

1.带参数

2.依次添加多个参数

 

3.一次添加多个参数不严谨

 

--------------------------------------------------------------------

连接池:

1.连接池

2.禁用连接池

3.连接池总结

需要记住的,到时找地方插入

 

 对sqlserver的延伸:

------------------

http://www.w3school.com.cn/sql/sql_datatypes.asp

http://www.cnblogs.com/fttbfttb/articles/1510386.html

 

c#  + sql语句:

在网上下载东西时不知道进入了什么病毒,我准备的小例子都白白牺牲了,我找出来个几个残留的例子,给大家讲解吧。由浅入深…..

  1. 查找学生程序

这个小程序是我大学刚毕业进去公司,面试的一道基础小题,输入一个人名会出现他的名字科目成绩。数据库也要自己写,虽然对于现在来说很简单,但是我当时真的很害怕。这个小例子假如看不懂也不重要,只是先给大家一个“感觉”。

 1 using system;
 2 using system.collections.generic;
 3 using system.componentmodel;
 4 using system.data;
 5 using system.drawing;
 6 using system.linq;
 7 using system.text;
 8 using system.windows.forms;
 9 using system.data.sqlclient;
10 
11 namespace 学¡ì生¦¨²成¨¦绩¡§
12 {
13     public partial class form1 : form
14     {
15         public form1()
16         {
17             initializecomponent();
18         }
19 
20         private void form1_load(object sender, eventargs e)
21         {
22             button1.text = "查¨¦看¡ä";
23             label1.text = "姓?名?:êo";
24             label2.text = "课?程¨¬:êo";
25             label3.text = "成¨¦绩¡§:êo";
26             label4.text = "选?择?:êo";
27         }
28 
29         private void button1_click(object sender, eventargs e)
30         {
31             using (sqlconnection conn = new sqlconnection("server = .;database=lianxi;uid =sa;pwd=sa123456"))
32             {
33                 conn.open();
34 
35                 using (sqlcommand cmd = conn.createcommand())
36                 {
37                     cmd.commandtext = "select name,kname,cj from s,k,cj where(s.sid = cj.sid and k.kid = cj.kid and name = @name)";
38                     cmd.parameters.add(new sqlparameter("@name", combobox1.text));
39                     using (sqldatareader read = cmd.executereader())
40                     {
41                         while (read.read())
42                         {
43                             string sname = read.getstring(0);
44                             string kname = read.getstring(1);
45                             long cj = read.getint64(2);
46                             textbox1.text = sname;
47                             textbox2.text = kname;
48                             textbox3.text = convert.tostring(cj);
49                         }
50                     }
51                 }
52             }
53         }
54     }
55 }

 ---------------

代码损坏了,把图片放在这,年后把代码写下

sqlhelper:

数据的增删改查+dbnull

登录

--------------------

command存储过程

 1 use [lianxi]
 2 go
 3 /****** object:  storedprocedure [dbo].[sql_ku_nm]    script date: 01/22/2017 15:18:08 ******/
 4 set ansi_nulls on
 5 go
 6 set quoted_identifier on
 7 go
 8 alter procedure [dbo].[sql_ku_nm]    
 9     (
10     @name nchar(10)
11     )    
12 as    
13     insert cmd(
14         name
15     ) values(
16         @name
17     )
  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.data.sqlclient;
 10 using system.threading;
 11 
 12 namespace command存ä?储ä¡é过y程¨¬
 13 {
 14     public partial class form1 : form
 15     {
 16         public form1()
 17         {
 18             initializecomponent();
 19         }
 20 
 21         private void button1_click(object sender, eventargs e)
 22         {
 23             try
 24             {
 25                 using (sqlcommand cmd = conn.createcommand())
 26                 {
 27                     //cmd.commandtext = "insert into cmd(name) values('"+textbox1.text+"')";//sql语®?句?执¡ä行d的ì?
 28 
 29                     //下?面?用®?存ä?储ä¡é过y程¨¬执¡ä行d
 30                     cmd.commandtype = commandtype.storedprocedure;
 31                     cmd.commandtext = "sql_ku_nm";
 32                     cmd.parameters.add(new sqlparameter("@name", textbox1.text));
 33                     //commandtimeout 等쨨待äy超?时º¡à
 34                     cmd.commandtimeout = 30 * 60;//以°?秒?为a单죤位?  这a是º?半ã?个?小?时º¡à 超?时º¡à发¤¡é生¦¨²异°¨¬常¡ê
 35 
 36                     //这a不?懂? 查¨¦查¨¦
 37                     //sqlcommandbuilder 
 38                     //sqlconnectionstringbuilder
 39 
 40                     cmd.executenonquery();
 41                 }
 42             }
 43             catch (exception ex)
 44             {
 45                 messagebox.show(ex.message);
 46             }
 47         }
 48 
 49         private void btn_null_click(object sender, eventargs e)
 50         {
 51             try
 52             {
 53                 using (sqlcommand cmd = conn.createcommand())
 54                 {
 55                     cmd.commandtext = "select * from cmd ";
 56                     sqldatareader read = cmd.executereader();
 57                     int i = 2;
 58                     while (read.read())
 59                     {
 60                         if (!read.isdbnull(i))//isdbnull(i) i代䨲表ਪ判d断?第쨲几?列¢d
 61                         {
 62                             string strname = read.getstring(1);
 63                             string strpwd = read.getstring(2);
 64                             listbox1.items.addrange(new object[] { strname + " " + strpwd });
 65                             //listbox1.items.add(strname);
 66                             //listbox1.items.add(strpwd);
 67                         }
 68                     }
 69                 }
 70             }
 71             catch (exception ex)
 72             {
 73                 messagebox.show(ex.message);
 74             }
 75         }
 76         sqlconnection conn;
 77         private void btn_conn_click(object sender, eventargs e)
 78         {
 79             string sqlconn = "server =.;database =lianxi;uid=sa;pwd=sa123456";
 80             conn = new sqlconnection(sqlconn);
 81             conn.open();
 82             txtconn.text = conn.state.tostring();
 83         }
 84 
 85         sqldatareader read;
 86         private void btn_jieguoji_click(object sender, eventargs e)
 87         {
 88             listbox2.items.clear();
 89             listbox3.items.clear();
 90             try
 91             {
 92                 using (sqlcommand cmd = conn.createcommand())
 93                 {
 94                     cmd.commandtext = @"select * from cmd 
 95                                         select * from b2";//select * from cmd
 96                     read = cmd.executereader();
 97                     int i = 0;
 98 
 99                     do
100                     {
101                         while (read.read())
102                         {
103                             string strname = read.getstring(1);
104                             string strpwd = read.getstring(2);
105                             if (i == 0)
106                                 listbox2.items.addrange(new object[] { strname + " " + strpwd });
107                             else
108                                 listbox3.items.addrange(new object[] { strname + " " + strpwd });
109                         }
110                         i++;
111                     } while (read.nextresult());//进?入¨?下?一°?个?结¨¢果?集¡¥
112                 }
113             }
114             catch (exception ex)
115             {
116                 messagebox.show(ex.message);
117             }
118             finally
119             {
120                 if (read != null)
121                     read.close();
122             }
123         }
124 
125         private void btn_index_click(object sender, eventargs e)
126         {
127             try
128             {
129                 using (sqlcommand cmd = conn.createcommand())
130                 {
131                     cmd.commandtext = @"select * from cmd";
132                     read = cmd.executereader();
133 
134                     while (read.read())
135                     {
136                         string strname = read.getstring(read.getordinal("name"));
137                         string strpwd = read.getstring(read.getordinal("pwd"));
138                         listbox4.items.add(strname + " " + strpwd);
139                     }
140                 }
141             }
142             catch (exception ex)
143             {
144                 messagebox.show(ex.message);
145             }
146             finally
147             {
148                 if (read != null)
149                     read.close();
150             }
151         }
152 
153         private void button2_click(object sender, eventargs e)
154         {
155             try
156             {
157                 using (sqlcommand cmd = conn.createcommand())
158                 {
159                     cmd.commandtext = @"select * from cmd where name = @name";
160                     cmd.parameters.add(new sqlparameter("@name", txt_yn.text));
161                     read = cmd.executereader();
162 
163                     bool isex = read.hasrows;//判d断?是º?否¤?存ä?在¨²记?录?
164                     int count = read.fieldcount;//返¤¦ì回?多¨¤少¦¨´字á?段?,多¨¤少¦¨´列¢d
165                     if (isex)
166                     {
167                         label1.text = "存ä?在¨²" + " " + count + "个?列¢d";
168                     }
169                     else
170                         label1.text = "不?存ä?在¨²";
171                 }
172             }
173             catch (exception ex)
174             {
175                 messagebox.show(ex.message);
176             }
177             finally
178             {
179                 if (read != null)
180                     read.close();
181             }
182         }
183     }
184 }

------------

各种显示:

  1 using system;
  2 using system.collections.generic;
  3 using system.componentmodel;
  4 using system.data;
  5 using system.drawing;
  6 using system.linq;
  7 using system.text;
  8 using system.windows.forms;
  9 using system.data.sqlclient;
 10 
 11 namespace 练¢¡¤习¡ã
 12 {
 13     public partial class form1 : form
 14     {
 15         public form1()
 16         {
 17             initializecomponent();
 18         }
 19 
 20         private void btnalldata_click(object sender, eventargs e)
 21         {
 22             listdata.items.clear();
 23             using (sqlconnection conn = new sqlconnection("server=.;database=lianxi;uid=sa;password=sa123456"))
 24             {
 25                 conn.open();
 26                 using (sqlcommand cmd = conn.createcommand())
 27                 {
 28                     cmd.commandtext = "select *from tt";
 29                     using (sqldatareader read = cmd.executereader())
 30                         while (read.read())
 31                         {
 32                             string str1 = read.getvalue(0).tostring();
 33                             string str2 = read.getvalue(1).tostring();
 34                             listdata.items.add(str1 + "\t" + str2);
 35                         }
 36                 }
 37             }
 38         }
 39         string connstring = @"data source=.\sqlexpress;initial catalog=book;integrated security=true";
 40         private void btnone_click(object sender, eventargs e)
 41         {
 42             listdata.items.clear();
 43             using (sqlconnection conn = new sqlconnection("server=.;database=lianxi;uid=sa;pwd=sa123456"))
 44             {
 45                 conn.open();
 46                 using (sqlcommand cmd = conn.createcommand())
 47                 {
 48                     //cmd.commandtext = "select *from tt where id=(select min(id) from tt)";//这a两¢?种?一°?样¨´
 49                     cmd.commandtext = "select top 1 * from tt ";
 50                     using (sqldatareader read = cmd.executereader())
 51                         while (read.read())
 52                         {
 53                             string str1 = read.getvalue(0).tostring();
 54                             string str2 = read.getvalue(1).tostring();
 55                             listdata.items.add(str1 + "\t" + str2);
 56                         }
 57                 }
 58             }
 59         }
 60 
 61         private void btnzh_click(object sender, eventargs e)
 62         {
 63             listdata.items.clear();
 64             using (sqlconnection conn = new sqlconnection("data source=.;initial catalog=lianxi;integrated security=true"))
 65             {
 66                 conn.open();
 67                 using (sqlcommand cmd = conn.createcommand())
 68                 {
 69                     //cmd.commandtext = "select top 1 * from tt order by id desc ";
 70                     cmd.commandtext = "select *from tt where id = (select max(id) from tt)";
 71                     using (sqldatareader read = cmd.executereader())
 72                         while (read.read())
 73                         {
 74                             string str1 = read.getvalue(0).tostring();
 75                             string str2 = read.getvalue(1).tostring();
 76                             listdata.items.add(str1 + "\t" + str2);
 77                         }
 78                 }
 79             }
 80         }
 81 
 82         private void btnname_click(object sender, eventargs e)
 83         {
 84             listdata.items.clear();
 85             using (sqlconnection conn = new sqlconnection("server=.;database =lianxi;uid = sa;pwd=sa123456"))
 86             {
 87                 conn.open();
 88                 using (sqlcommand cmd = conn.createcommand())
 89                 {
 90                     if (txtid.text != "")
 91                     {
 92                         cmd.commandtext = "select name from tt where id =" + txtid.text;
 93 
 94                         using (sqldatareader read = cmd.executereader())
 95                             while (read.read())
 96                             {
 97                                 listdata.items.add(read.getvalue(0).tostring());
 98                             }
 99                     }
100                 }
101             }
102         }
103 
104         private void btndategrid_click(object sender, eventargs e)
105         {
106             datagridview1.columns.clear();
107             datagridview1.columns.add("name", "时º¡à间?");
108             datagridview1.columns.add("name", "数ºy字á?");
109 
110             using (sqlconnection conn = new sqlconnection("server= .;database=lianxi;uid=sa;pwd=sa123456"))
111             {
112                 conn.open();
113                 using (sqlcommand cmd = conn.createcommand())
114                 {
115                     cmd.commandtext = "select time from b4 where time>=@datatime";
116                     cmd.parameters.add(new sqlparameter("@datatime", "2016-09-26 16:34:41.000"));
117                     datetime datetime = datetime.now;
118                     int ii = 0;
119                     using (sqldatareader read = cmd.executereader())
120                     {
121                         while (read.read())
122                         {
123                             datetime = read.getdatetime(0);
124                             datagridview1.rows.add(datetime, ii++);
125                         }
126                     }
127                 }
128             }
129         }
130     }
131 }

------------------

1.常用函数

 1 //    avg函¡¥数ºy  求¨®平?均¨´值¦ì
 2             //    count函¡¥数ºy 求¨®行d数ºy
 3             //    first函¡¥数ºy 指?定¡§字á?段?中d第쨲一°?个?记?录?的ì?值¦ì  经-常¡ê用®?order by语®?句?进?行d排?序¨°
 4             //    last函¡¥数ºy 指?定¡§的ì?字á?段?中d最á?后¨®一°?个?记?录?的ì?值¦ì
 5             //    max函¡¥数ºy   返¤¦ì回?一°?列¢d中d的ì?最á?大䨮值¦ì null值¦ì不?包㨹括¤¡§在¨²计?算?机¨²中d
 6             //    min函¡¥数ºy   返¤¦ì回?一°?列¢d中d的ì?最á?小?值¦ì null值¦ì不?包㨹括¤¡§在¨²计?算?机¨²中d
 7             //    sum函¡¥数ºy   返¤¦ì回?数ºy值¦ì列¢d的ì?总ᨹ数ºy(ꡧ总ᨹ额?)ê?
 8             //    group by语®?句?  永®¨¤远?结¨¢合?合?计?函¡¥数ºy,ê?根¨´据y一°?个?或¨°多¨¤个?列¢d对?结¨¢果?集¡¥进?行d分¤?组ᨦ
 9 
10             //    having 子ᨮ句?   where关?键¨¹字á?无t法¤¡§与®?合?计?函¡¥数ºy一°?起e使º1用®?
11             //        例¤y子ᨮ:êo
12             //        我¨°们?希¡ê望ª?查¨¦找¨°订?单죤总ᨹ金e额?少¦¨´于®¨² 2000 的ì?客¨ª户¡ì。¡ê
13             //        我¨°们?使º1用®?如¨?下? sql 语®?句?:êo 
14             //        select customer,sum(orderprice) from orders 
15             //        group by customer 
16             //        having sum(orderprice)<2000 
17 
18             //    mid(ꡧ)ê?函¡¥数ºy     从䨮文?本à?字á?段?中d提¬¨¢取¨?字á?符¤?            
19             //    select mid(column_name,start[,length]) from table_name参?数ºy 描¨¨述º? 
20             //    column_name 必à?需¨¨。¡ê要°a提¬¨¢取¨?字á?符¤?的ì?字á?段?。¡ê 
21             //    start 必à?需¨¨。¡ê规?定¡§开a始º?位?置?(ꡧ起e始º?值¦ì是º? 1)ê?。¡ê
22             //    length 可¨¦选?。¡ê要°a返¤¦ì回?的ì?字á?符¤?数ºy。¡ê如¨?果?省º?略?,ê?则¨° mid() 函¡¥数ºy返¤¦ì回?剩º¡ê余®¨¤文?本à?。¡ê 
23 
24             //    len(ꡧ)ê?函¡¥数ºy     返¤¦ì回?文?本à?字á?段?中d值¦ì的ì?长¡è度¨¨
25             //        select len(column_name) from table_name 

2.检测要删除的表是否存在,将其删除

1 --检查要删除的表是否存在
2 use 库名
3 go
4 select *from sysobjects --通过系统表 显示出所有存在的表
5 
6 --如果存在就将其表删除,否则不执行删除
7 if exists(select *from sysobjects where name = '要删除的表名')
8 drop table ‘要删除的表名’
9 go

3.索引

http://www.cnblogs.com/knowledgesea/p/3672099.html

 1 --create index 索引名 on 表名(列名)
 2 --sp_helpindex 表名
 3 --drop index 表名.索引名
 4 
 5 create index b1_indexname on b1(age)
 6 sp_helpindex b1 --查看表b1内的所有索引
 7 drop index b1.b1_indexname --删除索引
 8 select b1_indexname from b1
 9 
10 
11 唯一索引:
12 
13 唯一索引不允许两行具有相同的索引值。
14 
15 如果现有数据中存在重复的键值,则大多数数据库都不允许将新创建的唯一索引与表一起保存。当新数据将使表中的键值重复时,数据库也拒绝接受此数据。例如,如果在stuinfo表中的学员员身份证号(stuid) 列上创建了唯一索引,则所有学员的身份证号不能重复。
16 
17 提示:创建了唯一约束,将自动创建唯一索引。尽管唯一索引有助于找到信息,但为了获得最佳性能,建议使用主键约束或唯一约束。
18 
19  
20 
21 主键索引:
22 
23 在数据库关系图中为表定义一个主键将自动创建主键索引,主键索引是唯一索引的特殊类型。主键索引要求主键中的每个值是唯一的。当在查询中使用主键索引时,它还允许快速访问数据。
24 
25  
26 
27 聚集索引(clustered index)
28 
29 在聚集索引中,表中各行的物理顺序与键值的逻辑(索引)顺序相同。表只能包含一个聚集索引。例如:汉语字(词)典默认按拼音排序编排字典中的每页页码。拼音字母a,b,c,d……x,y,z就是索引的逻辑顺序,而页码1,2,3……就是物理顺序。默认按拼音排序的字典,其索引顺序和逻辑顺序是一致的。即拼音顺序较后的字(词)对应的页码也较大。如拼音“ha”对应的字(词)页码就比拼音“ba” 对应的字(词)页码靠后。
30 
31  
32 
33 非聚集索引(non-clustered)
34 
35 如果不是聚集索引,表中各行的物理顺序与键值的逻辑顺序不匹配。聚集索引比非聚集索引(nonclustered index)有更快的数据访问速度。例如,按笔画排序的索引就是非聚集索引,“1”画的字(词)对应的页码可能比“3”画的字(词)对应的页码大(靠后)。
36 
37 提示:sql server中,一个表只能创建1个聚集索引,多个非聚集索引。设置某列为主键,该列就默认为聚集索引 
38 -----------------------------------------
39 create [unique] [clustered|nonclustered]  
40     index   index_name
41      on table_name (column_name…)
42       [with fillfactor=x]
43 --       unique表示唯一索引,可选
44 --       clustered、nonclustered表示聚集索引还是非聚集索引,可选
45 --       with fillfactor表示填充因子,指定一个0到100之间的值,该值指示索引页填满的空间所占的百分比
46 -------------------------------------
47 use studb
48 go
49 if exists (select name from sysindexes 
50           where name = 'ix_writtenexam')
51    drop index stumarks.ix_writtenexam  
52 /*--笔试列创建非聚集索引:填充因子为30%--*/
53 create nonclustered index ix_writtenexam
54      on stumarks(writtenexam)
55           with fillfactor= 30
56 go
57 /*-----指定按索引 ix_writtenexam 查询----*/
58 select * from stumarks  (index=ix_writtenexam)
59     where writtenexam between 60 and 90
60 虽然我们可以指定sql server按哪个索引进行数据查询,但一般不需要我们人工指定。sql server将会根据我们创建的索引,自动优化查询 。
61 ---------------------------
62 select *from b1 index=pk_b1

4.约束:

约束类型:
主键约束:要求主键列不能为空,要求主键列为一
非空约束:要求该列不能存在空值
唯一约束:要求该列的值必须是唯一的,允许为空,但只能出一同个空值
检查约束:限制某列取值的范围是否合适
默认约束:设计某列的默认值
外键约束:用于在两表之间建立关系,需要指定引用主表是哪一列

语法:
alter table 表明
  add constraint 约束名 约束类型 具体的约束说明
约束的取名规则推荐采纳:约束类型_约束列

主键(primary key)约束:如 pk_userld
唯一(unique key)约束: 如 uq_usercardid
默认(default key)约束: 如 df_userpasspwd
检查(check key)约束: 如ck_gender
外键(foreign key)约束: 如fk_sortid

--------------------------------------------------
use lianxi
go 

--为用户表b1添加约束
--add constraint 约束名 约束类型 具体的约束说明
alter table b1
add constraint pk_b1 primary key (id), -- 添加主键
    constraint uq_b1 unique(身份证号), -- 添加唯一主键
    constraint df_b1 default(0) for 性别, --添加默认主键
    constraint ck_b1 check(age>10 and age<55), --添加检查主键 and是代表 和,or代表 或
    constraint fk_b1 foreign key(name) references b2(name) -- 添加外键,引用的b2表中的name列,b2(name)约束了b1(name)
    go --批处理
    
    --注意1:外键约束 注意类型,长度必须与引用的主键列的类型 长度完全一致
    --注意2:外键约束 注意类型引用的表中必须有主键列
    
---------------------------------------------------------
向已有数据中添加约束
语法:
alter table 表名 with nocheck
    add constraint 约束名 约束类型 具体约束说明
    
对表中现有的数据不做检查
只对添加约束之后在录入的数据进行检查

alter table b1 with nocheck
    add constraint ck_b1身份证号 check(len(身份证号)=18)
    go
------------------------------------------------------------
删除约束
语法:
use lianxi
alter table 表名
  drop constraint 约束名
go

---------------------------------------------------------------
这个不属于约束了
关系图:
主要是图上连线  
假如关系图不成功就是用一下系统自带的存储过程
exec sp_changedbowner sa
go

5.视图:

个人理解:
    和数据表差不多,本质不同,数据表是实际存储记录的地方
    视图不保存任何记录 它存储实际上是查询语句,视图源于数据表


--创建视图
 create view view_1
 as 
 select *from b1

--修改视图
 alter view view_1
 as
 select *from b1,b3,b4

--删除视图
drop view view_old

--修改视图名称
exec  view_1  view_oldname   view_newname

--查看视图
select  name  from view_name

--显示视图
select *from view_1

注意事项

      每个视图中可以使用多个表

      与查询相似,一个视图可以嵌套另一个视图,但最好不要超过3层。

      视图定义中  select 语句不能包括一下内容

            order by 字句,除非在select 语句的选择列中也有一个top字句

            into 关键字

            引用临时表或表变量
create view view_name 
as 
select title, au_lname, price, pub_id 
from view_old

----------不同服务器上的------------

视图可用于在多个数据库或 microsoft? sql server? 2000 实例间对数据进行分区。分区视图可用于在整个服务器组内分布数据库处理。服务器组具有与服务器聚集相同的性能优点,并可用于支持最大的 web 站点或公司数据中心的处理需求。原始表被细分为多个成员表,每个成员表包含原始表的行子集。每个成员表可放置在不同服务器的数据库中。每个服务器也可得到分区视图。分区视图使用 transact-sql union 运算符,将在所有成员表上选择的结果合并为单个结果集,该结果集的行为与整个原始表的复本完全一样。例如在三个服务器间进行表分区。在第一个服务器上定义如下的分区视图:

create view partitionedview as 
select * 
from mydatabase.dbo.partitiontable1 
union all 
select * 
from server2.mydatabase.dbo.partitiontable2 
union all 
select * 
from server3.mydatabase.dbo.partitiontable3

在其它两个服务器上定义类似的分区视图。利用这三个视图,三个服务器上任何引用 partitionedview 的 transact-sql 语句都将看到与原始表中相同的行为。似乎每个服务器上都存在原始表的复本一样,而实际上每个表只有一个成员表和分区视图。有关更多信息,请参见视图使用方案。

---------------------------------
 

视图的优缺点

     优点: 简单、 安全、逻辑数据独立

     缺点: 性能,修改限制

           如果视图中存在函数或涉及复杂的多表查询,那么用户在查询视图的过程中会花费一定的时间。

           对于简单的视图可以使用update 语句更新,如果对于复杂的视图可能就不能使用了。删除亦是如此。所以对于视图的用法最好只停留到查询上面。

6.触发器:

 create trigger newtrigger1     --创建的表明
on b2                --操作的表明
for update            --用到的操作
as
if update(name)            --字段内数据是否改动
print('名字改变')
update b2 set name = '毕毕' where id >=3

--上面的是触发器代码
--下面更改name字段数据之后 
update b2 set name='bccb' where id>=3





drop trigger trigger_name    --删除触发器

--查看数据库中已有触发器
use lianxi
go
select * from sysobjects where xtype='tr'


--修改触发器
 alter trigger trigger_name
           on {table_name | view_name}
           {for | after | instead of }
           [ insert, update,delete ]
           as
           sql_statement


rollback transaction   --回滚﹐避免加入


--下面的这些有点懵
4﹕在orders表建立一个更新触发器﹐监视orders表的订单日期(orderdate)列﹐使其不能手工修改.
create trigger orderdateupdate
on orders
after update
as
if update(orderdate)
begin
raiserror(' orderdate cannot be modified',10,1)
rollback transaction
end

出现下述情况时,事务会回滚 
1.手工用rollback   tran回滚 
2.设置了set   xact_abort   on后,出错时会自动回滚 
3.事务提交前,电脑出现故障,或者sql意外终止,事务会自动回滚

set xact_abort on   ---如果不设置该项为on,在sql中默认为off,那么只只回滚产生错误的 transact-sql 语句;设为on,回滚整个事务

begin tran t1 ---启动一个事务

update [water].[dbo].[errorinf]
set errormessage='test'
where id=6

insert into [water].[dbo].[errorinf]([id],errormessage,[description])
values(1,'test1','test1')

commit tran t1  ---提交事务 

----------------------------------
--下面比较麻烦,手动回滚
begin tran 

insert into dbo.area values('1111')
if @@error>0
  rollback

insert into dbo.area values('2222')
if @@error>0
  rollback

select 1/0
if @@error>0
  rollback

insert into dbo.area values('333')
if @@error>0
  rollback

commit 

------------------------------------------
事务(transaction)是访问并可能更新数据库中各种数据项的一个程序执行单元(unit)。事务通常由高级数据库操纵语言或编程语言(如sql,c++或java)书写的用户程序的执行所引起,并用形如begin transaction和end transaction语句(或函数调用)来界定。事务由事务开始(begin transaction)和事务结束(end transaction)之间执行的全体操作组成。

当一个事务的某一个操作发生问题时,整个事务可以回滚掉,就像没有做任何操作一样。这就是事务回滚。
如果一个事务的所有操作均成功,则就可以提交事务,保证事务的完整性。

应用程序主要通过指定事务启动和结束的时间来控制事务。

以ms sql server的transac-sql语言为例,
事务启动: 
begin tran [ saction ] [ transaction_name | @tran_name_variable [ with mark [ 'description' ] ] ]

结束事务
可以使用 commit 或 rollback 语句结束事务。

1 事务的提交
begin transaction t1
insert tabel1 ...
update table2 ...
...
/* 当所有成功操作完成,提交事务 */
commit tran t1

2 事务的回滚
begin transaction t1
insert tabel1 ...
... 
/* 当发生错误或事务被取消, 回滚事务 */
rollback tran t1

-------------------------------

总结:事务回滚的几种方法
if exists(...)
rollback
..

----
set xact_abort on
begin t1
--执行的语句
commit t1

----------------------------------

--开启、关闭触发器
disable trigger [触发器名] on database --禁用触发器 

enable trigger [触发器名] on database --开启触发器 

-----------------------------------

查询当前数据库中有多少触发器,以方便我进行数据库维护,只需要运行:
 select * from sysobjects where xtype='tr'

---------------------------------------

查看某一个触发器的内容,直接运行:
exec sp_helptext [触发器名]

------------------------------------

更改触发器的话,只需要将开始的create创建变为alter

----------------

三层架构----还拿登录

 

app.config:配置文件,链接数据库字符串

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionstrings>
    <add name="conn_sql" connectionstring="server=.;database=登录; user id=sa; password=byl19930314"/>
  </connectionstrings>
</configuration>

form1:ui应用层

 model:使数据在三层中传输  

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 三层架构_登录
 7 {
 8     //添加类:userinfo  model实体作用:封装数据,使数据在三层中传输 ,更倾向于业务逻辑层
 9     public class model
10     {
11         //定义用户属性
12         public int id { get; set; }
13         public string username { get; set; }
14         public string password { get; set; }
15     }
16 }

sqlhelp:执行数据库命令操作

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.data.sqlclient;
 6 using system.data;
 7 using system.configuration;
 8 
 9 namespace 三层架构_登录
10 {
11     public class sqlhelp
12     {
13         public static sqldatareader executedatatable(sqlconnection conn, string sql, params sqlparameter[] parameters)
14         {
15             sqldatareader reader;
16 
17             sqlcommand cmd = conn.createcommand();
18             cmd.commandtext = sql;
19             cmd.parameters.addrange(parameters);
20             reader = cmd.executereader();
21             // conn.close();             
22             return reader;
23         }
24     }
25 }

bll:业务逻辑层

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 
 6 namespace 三层架构_登录
 7 {
 8     public class bll
 9     {
10         public model userlogin(string username, string password)
11         {
12             dal udao = new dal();//实例化dal层
13             model user = udao.selectuser(username, password);
14 
15             //不需访问数据源直接执行业务逻辑
16             if (user != null)
17             {
18                 return user;
19             }
20             else
21             {
22                 throw new exception("登陆失败");
23             }
24         }
25     }
26 }

dal:数据访问层

 1 using system;
 2 using system.collections.generic;
 3 using system.linq;
 4 using system.text;
 5 using system.data.sqlclient;
 6 using system.data;
 7 using system.configuration;
 8 
 9 namespace 三层架构_登录
10 {
11     public class dal
12     {
13         private static string connstr = configurationmanager.connectionstrings["conn_sql"].connectionstring;
14 
15         public model selectuser(string username, string password)
16         {
17             using (sqlconnection conn = new sqlconnection(connstr))
18             {
19                 conn.open();
20                 sqldatareader reader = sqlhelp.executedatatable(conn, "select id,username,password from 登录表 where username=@username and password=@password"
21                       , new sqlparameter[] { new sqlparameter("@username", username), new sqlparameter("@password", password) });
22 
23                 model user = null;
24 
25                 //读取具体的数据
26                 while (reader.read())
27                 {
28                     if (user == null)
29                     {
30                         user = new model();
31                     }
32                     //读取查询到的数据
33                     user.id = reader.getint32(0);
34                     user.username = reader.getstring(1);
35                     user.password = reader.getstring(2);
36                 }
37                 reader.close();
38                 return user;
39             }
40         }
41     }
42 }

 数据表:

 

 

 

--------------------------

网上查的sqlserver大全

1、说明:创建数据库
create database database-name 
2、说明:删除数据库
drop database dbname
3、说明:备份sql server
--- 创建 备份数据的 device
use master
exec sp_addumpdevice 'disk', 'testback', 'c:\mssql7backup\mynwind_1.dat'
--- 开始 备份
backup database pubs to testback 
4、说明:创建新表
create table tabname(col1 type1 [not null] [primary key],col2 type2 [not null],..)
根据已有的表创建新表: 
a:create table tab_new like tab_old (使用旧表创建新表)
b:create table tab_new as select col1,col2… from tab_old definition only
5、说明:删除新表
drop table tabname 
6、说明:增加一个列
alter table tabname add column col type
注:列增加后将不能删除。db2中列加上后数据类型也不能改变,唯一能改变的是增加varchar类型的长度。
7、说明:添加主键: alter table tabname add primary key(col) 
说明:删除主键: alter table tabname drop primary key(col) 
8、说明:创建索引:create [unique] index idxname on tabname(col….) 
删除索引:drop index idxname
注:索引是不可更改的,想更改必须删除重新建。
9、说明:创建视图:create view viewname as select statement 
删除视图:drop view viewname
10、说明:几个简单的基本的sql语句
选择:select * from table1 where 范围
插入:insert into table1(field1,field2) values(value1,value2)
删除:delete from table1 where 范围
更新:update table1 set field1=value1 where 范围
查找:select * from table1 where field1 like ’%value1%’ ---like的语法很精妙,查资料!
排序:select * from table1 order by field1,field2 [desc]
总数:select count as totalcount from table1
求和:select sum(field1) as sumvalue from table1
平均:select avg(field1) as avgvalue from table1
最大:select max(field1) as maxvalue from table1
最小:select min(field1) as minvalue from table1
11、说明:几个高级查询运算词
a: union 运算符 
union 运算符通过组合其他两个结果表(例如 table1 和 table2)并消去表中任何重复行而派生出一个结果表。当 all 随 union 一起使用时(即 union all),不消除重复行。两种情况下,派生表的每一行不是来自 table1 就是来自 table2。 
b: except 运算符 
except运算符通过包括所有在 table1 中但不在 table2 中的行并消除所有重复行而派生出一个结果表。当 all 随 except 一起使用时 (except all),不消除重复行。
c: intersect 运算符
intersect运算符通过只包括 table1 和 table2 中都有的行并消除所有重复行而派生出一个结果表。当 all随 intersect 一起使用时 (intersect all),不消除重复行。 
注:使用运算词的几个查询结果行必须是一致的。 
12、说明:使用外连接 
a、left (outer) join: 
左外连接(左连接):结果集几包括连接表的匹配行,也包括左连接表的所有行。 
sql: select a.a, a.b, a.c, b.c, b.d, b.f from a left out join b on a.a = b.c
b:right (outer) join: 
右外连接(右连接):结果集既包括连接表的匹配连接行,也包括右连接表的所有行。 
c:full/cross (outer) join: 
全外连接:不仅包括符号连接表的匹配行,还包括两个连接表中的所有记录。
12、分组:group by:
     一张表,一旦分组 完成后,查询后只能得到组相关的信息。
    组相关的信息:(统计信息) count,sum,max,min,avg  分组的标准)
    在sqlserver中分组时:不能以text,ntext,image类型的字段作为分组依据
    在selecte统计函数中的字段,不能和普通的字段放在一起;
13、对数据库进行操作:
    分离数据库: sp_detach_db;附加数据库:sp_attach_db 后接表明,附加需要完整的路径名
14.如何修改数据库的名称:
sp_renamedb 'old_name', 'new_name'
 
二、提升
1、说明:复制表(只复制结构,源表名:a 新表名:b) (access可用)
法一:select * into b from a where 1<>1(仅用于sqlserver)
法二:select top 0 * into b from a
2、说明:拷贝表(拷贝数据,源表名:a 目标表名:b) (access可用)
insert into b(a, b, c) select d,e,f from b;
3、说明:跨数据库之间表的拷贝(具体数据使用绝对路径) (access可用)
insert into b(a, b, c) select d,e,f from b in ‘具体数据库’ where 条件
例子:..from b in '"&server.mappath(".")&"\data.mdb" &"' where..
4、说明:子查询(表名1:a 表名2:b)
select a,b,c from a where a in (select d from b ) 或者: select a,b,c from a where a in (1,2,3)
5、说明:显示文章、提交人和最后回复时间
select a.title,a.username,b.adddate from table a,(select max(adddate) adddate from table where table.title=a.title) b
6、说明:外连接查询(表名1:a 表名2:b)
select a.a, a.b, a.c, b.c, b.d, b.f from a left out join b on a.a = b.c
7、说明:在线视图查询(表名1:a )
select * from (select a,b,c from a) t where t.a > 1;
8、说明:between的用法,between限制查询数据范围时包括了边界值,not between不包括
select * from table1 where time between time1 and time2
select a,b,c, from table1 where a not between 数值1 and 数值2
9、说明:in 的使用方法
select * from table1 where a [not] in (‘值1’,’值2’,’值4’,’值6’)
10、说明:两张关联表,删除主表中已经在副表中没有的信息 
delete from table1 where not exists ( select * from table2 where table1.field1=table2.field1 )
11、说明:四表联查问题:
select * from a left inner join b on a.a=b.b right inner join c on a.a=c.c inner join d on a.a=d.d where .....
12、说明:日程安排提前五分钟提醒 
sql: select * from 日程安排 where datediff('minute',f开始时间,getdate())>5
13、说明:一条sql 语句搞定数据库分页
select top 10 b.* from (select top 20 主键字段,排序字段 from 表名 order by 排序字段 desc) a,表名 b where b.主键字段 = a.主键字段 order by a.排序字段
具体实现:
关于数据库分页:
  declare @start int,@end int 
  @sql  nvarchar(600)
  set @sql=’select top’+str(@end-@start+1)+’+from t where rid not in(select top’+str(@str-1)+’rid from t where rid>-1)’
  exec sp_executesql @sql

注意:在top后不能直接跟一个变量,所以在实际应用中只有这样的进行特殊的处理。rid为一个标识列,如果top后还有具体的字段,这样做是非常有好处的。因为这样可以避免 top的字段如果是逻辑索引的,查询的结果后实际表中的不一致(逻辑索引中的数据有可能和数据表中的不一致,而查询时如果处在索引则首先查询索引)
14、说明:前10条记录
select top 10 * form table1 where 范围
15、说明:选择在每一组b值相同的数据中对应的a最大的记录的所有信息(类似这样的用法可以用于论坛每月排行榜,每月热销产品分析,按科目成绩排名,等等.)
select a,b,c from tablename ta where a=(select max(a) from tablename tb where tb.b=ta.b)
16、说明:包括所有在 tablea中但不在 tableb和tablec中的行并消除所有重复行而派生出一个结果表
(select a from tablea ) except (select a from tableb) except (select a from tablec)
17、说明:随机取出10条数据
select top 10 * from tablename order by newid()
18、说明:随机选择记录
select newid()
19、说明:删除重复记录
1),delete from tablename where id not in (select max(id) from tablename group by col1,col2,...)
2),select distinct * into temp from tablename
  delete from tablename
  insert into tablename select * from temp
评价: 这种操作牵连大量的数据的移动,这种做法不适合大容量但数据操作
3),例如:在一个外部表中导入数据,由于某些原因第一次只导入了一部分,但很难判断具体位置,这样只有在下一次全部导入,这样也就产生好多重复的字段,怎样删除重复字段
alter table tablename
--添加一个自增列
add  column_b int identity(1,1)
 delete from tablename where column_b not in(
select max(column_b)  from tablename group by column1,column2,...)
alter table tablename drop column column_b
20、说明:列出数据库里所有的表名
select name from sysobjects where type='u' // u代表用户
21、说明:列出表里的所有的列名
select name from syscolumns where id=object_id('tablename')
22、说明:列示type、vender、pcs字段,以type字段排列,case可以方便地实现多重选择,类似select 中的case。
select type,sum(case vender when 'a' then pcs else 0 end),sum(case vender when 'c' then pcs else 0 end),sum(case vender when 'b' then pcs else 0 end) from tablename group by type
显示结果:
type vender pcs
电脑 a 1
电脑 a 1
光盘 b 2
光盘 a 2
手机 b 3
手机 c 3
23、说明:初始化表table1
truncate table table1
24、说明:选择从10到15的记录
select top 5 * from (select top 15 * from table order by id asc) table_别名 order by id desc
1、1=1,1=2的使用,在sql语句组合时用的较多
“where 1=1” 是表示选择全部    “where 1=2”全部不选,
如:
if @strwhere !='' 
begin
set @strsql = 'select count(*) as total from [' + @tblname + '] where ' + @strwhere 
end
else 
begin
set @strsql = 'select count(*) as total from [' + @tblname + ']' 
end 
我们可以直接写成
错误!未找到目录项。
set @strsql = 'select count(*) as total from [' + @tblname + '] where 1=1 安定 '+ @strwhere 2、收缩数据库
--重建索引
dbcc reindex
dbcc indexdefrag
--收缩数据和日志
dbcc shrinkdb
dbcc shrinkfile
3、压缩数据库
dbcc shrinkdatabase(dbname)
4、转移数据库给新用户以已存在用户权限
exec sp_change_users_login 'update_one','newname','oldname'
go
5、检查备份集
restore verifyonly from disk='e:\dvbbs.bak'
6、修复数据库
alter database [dvbbs] set single_user
go
dbcc checkdb('dvbbs',repair_allow_data_loss) with tablock
go
alter database [dvbbs] set multi_user
go
7、日志清除
set nocount on
declare @logicalfilename sysname,
 @maxminutes int,
 @newsize int

use tablename -- 要操作的数据库名
select  @logicalfilename = 'tablename_log', -- 日志文件名
@maxminutes = 10, -- limit on time allowed to wrap log.
 @newsize = 1  -- 你想设定的日志文件的大小(m)
setup / initialize
declare @originalsize int
select @originalsize = size 
 from sysfiles
 where name = @logicalfilename
select 'original size of ' + db_name() + ' log is ' + 
 convert(varchar(30),@originalsize) + ' 8k pages or ' + 
 convert(varchar(30),(@originalsize*8/1024)) + 'mb'
 from sysfiles
 where name = @logicalfilename
create table dummytrans
 (dummycolumn char (8000) not null)

declare @counter    int,
 @starttime datetime,
 @trunclog   varchar(255)
select @starttime = getdate(),
 @trunclog = 'backup log ' + db_name() + ' with truncate_only'
dbcc shrinkfile (@logicalfilename, @newsize)
exec (@trunclog)
-- wrap the log if necessary.
while @maxminutes > datediff (mi, @starttime, getdate()) -- time has not expired
 and @originalsize = (select size from sysfiles where name = @logicalfilename)  
 and (@originalsize * 8 /1024) > @newsize  
 begin -- outer loop.
select @counter = 0
 while   ((@counter < @originalsize / 16) and (@counter < 50000))
 begin -- update
 insert dummytrans values ('fill log') delete dummytrans
 select @counter = @counter + 1
 end
 exec (@trunclog)  
 end
select 'final size of ' + db_name() + ' log is ' +
 convert(varchar(30),size) + ' 8k pages or ' + 
 convert(varchar(30),(size*8/1024)) + 'mb'
 from sysfiles 
 where name = @logicalfilename
drop table dummytrans
set nocount off 
8、说明:更改某个表
exec sp_changeobjectowner 'tablename','dbo'
9、存储更改全部表
create procedure dbo.user_changeobjectownerbatch
@oldowner as nvarchar(128),
@newowner as nvarchar(128)
as
declare @name    as nvarchar(128)
declare @owner   as nvarchar(128)
declare @ownername   as nvarchar(128)
declare curobject cursor for 
select 'name'    = name,
   'owner'    = user_name(uid)
from sysobjects
where user_name(uid)=@oldowner
order by name
open   curobject
fetch next from curobject into @name, @owner
while(@@fetch_status=0)
begin     
if @owner=@oldowner 
begin
   set @ownername = @oldowner + '.' + rtrim(@name)
   exec sp_changeobjectowner @ownername, @newowner
end
-- select @name,@newowner,@oldowner
fetch next from curobject into @name, @owner
end
close curobject
deallocate curobject
go

10、sql server中直接循环写入数据
declare @i int
set @i=1
while @i<30
begin
    insert into test (userid) values(@i)
    set @i=@i+1
end
案例:
有如下表,要求就裱中所有沒有及格的成績,在每次增長0.1的基礎上,使他們剛好及格:
    name     score
    zhangshan    80
    lishi       59
    wangwu      50
    songquan    69
while((select min(score) from tb_table)<60)
begin
update tb_table set score =score*1.01
where score<60
if  (select min(score) from tb_table)>60
  break
 else
    continue
end
1.按姓氏笔画排序:
select * from tablename order by customername collate chinese_prc_stroke_ci_as //从少到多
2.数据库加密:
select encrypt('原始密码')
select pwdencrypt('原始密码')
select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同 encrypt('原始密码')
select pwdencrypt('原始密码')
select pwdcompare('原始密码','加密后密码') = 1--相同;否则不相同
3.取回表中字段:
declare @list varchar(1000),
@sql nvarchar(1000) 
select @list=@list+','+b.name from sysobjects a,syscolumns b where a.id=b.id and a.name='表a'
set @sql='select '+right(@list,len(@list)-1)+' from 表a' 
exec (@sql)
4.查看硬盘分区:
exec master..xp_fixeddrives
5.比较a,b表是否相等:
if (select checksum_agg(binary_checksum(*)) from a)
     =
    (select checksum_agg(binary_checksum(*)) from b)
print '相等'
else
print '不相等'
6.杀掉所有的事件探察器进程:
declare hcforeach cursor global for select 'kill '+rtrim(spid) from master.dbo.sysprocesses
where program_name in('sql profiler',n'sql 事件探查器')
exec sp_msforeach_worker '?'
7.记录搜索:
开头到n条记录
select top n * from 表
-------------------------------
n到m条记录(要有主索引id)
select top m-n * from 表 where id in (select top m id from 表) order by id   desc
----------------------------------
n到结尾记录
select top n * from 表 order by id desc
案例
例如1:一张表有一万多条记录,表的第一个字段 recid 是自增长字段, 写一个sql语句, 找出表的第31到第40个记录。
 select top 10 recid from a where recid not  in(select top 30 recid from a)
分析:如果这样写会产生某些问题,如果recid在表中存在逻辑索引。
    select top 10 recid from a where……是从索引中查找,而后面的select top 30 recid from a则在数据表中查找,这样由于索引中的顺序有可能和数据表中的不一致,这样就导致查询到的不是本来的欲得到的数据。
解决方案
1,用order by select top 30 recid from a order by ricid 如果该字段不是自增长,就会出现问题
2,在那个子查询中也加条件:select top 30 recid from a where recid>-1
例2:查询表中的最后以条记录,并不知道这个表共有多少数据,以及表结构。
set @s = 'select top 1 * from t   where pid not in (select top ' + str(@count-1) + ' pid  from  t)'
print @s      exec  sp_executesql  @s
9:获取当前数据库中的所有用户表
select name from sysobjects where xtype='u' and status>=0
10:获取某一个表的所有字段
select name from syscolumns where id=object_id('表名')
select name from syscolumns where id in (select id from sysobjects where type = 'u' and name = '表名')
两种方式的效果相同
11:查看与某一个表相关的视图、存储过程、函数
select a.* from sysobjects a, syscomments b where a.id = b.id and b.text like '%表名%'
12:查看当前数据库中所有存储过程
select name as 存储过程名称 from sysobjects where xtype='p'
13:查询用户创建的所有数据库
select * from master..sysdatabases d where sid not in(select sid from master..syslogins where name='sa')
或者
select dbid, name as db_name from master..sysdatabases where sid <> 0x01
14:查询某一个表的字段和数据类型
select column_name,data_type from information_schema.columns
where table_name = '表名'
15:不同服务器数据库之间的数据操作
--创建链接服务器
exec sp_addlinkedserver   'itsv ', ' ', 'sqloledb ', '远程服务器名或ip地址 ' 
exec sp_addlinkedsrvlogin  'itsv ', 'false ',null, '用户名 ', '密码 ' 
--查询示例
select * from itsv.数据库名.dbo.表名
--导入示例
select * into 表 from itsv.数据库名.dbo.表名
--以后不再使用时删除链接服务器
exec sp_dropserver  'itsv ', 'droplogins ' 
 
--连接远程/局域网数据(openrowset/openquery/opendatasource) 
--1、openrowset 
--查询示例
select * from openrowset( 'sqloledb ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名) 
--生成本地表
select * into 表 from openrowset( 'sqloledb ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名) 
 
--把本地表导入远程表
insert openrowset( 'sqloledb ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名) 
select *from 本地表
--更新本地表
update b 
set b.列a=a.列a 
 from openrowset( 'sqloledb ', 'sql服务器名 '; '用户名 '; '密码 ',数据库名.dbo.表名)as a inner join 本地表 b 
on a.column1=b.column1 
--openquery用法需要创建一个连接
--首先创建一个连接创建链接服务器 
exec sp_addlinkedserver   'itsv ', ' ', 'sqloledb ', '远程服务器名或ip地址 ' 
--查询
select * 
from openquery(itsv,  'select *  from 数据库.dbo.表名 ') 
--把本地表导入远程表
insert openquery(itsv,  'select *  from 数据库.dbo.表名 ') 
select * from 本地表
--更新本地表
update b 
set b.列b=a.列b 
from openquery(itsv,  'select * from 数据库.dbo.表名 ') as a  
inner join 本地表 b on a.列a=b.列a 
 
--3、opendatasource/openrowset 
select   * 
from   opendatasource( 'sqloledb ',  'data source=ip/servername;user id=登陆名;password=密码 ' ).test.dbo.roy_ta 
--把本地表导入远程表
insert opendatasource( 'sqloledb ',  'data source=ip/servername;user id=登陆名;password=密码 ').数据库.dbo.表名
select * from 本地表  
1.字符串函数 长度与分析用
1,datalength(char_expr) 返回字符串包含字符数,但不包含后面的空格
2,substring(expression,start,length) 取子串,字符串的下标是从“1”,start为起始位置,length为字符串长度,实际应用中以len(expression)取得其长度
3,right(char_expr,int_expr) 返回字符串右边第int_expr个字符,还用left于之相反
4,isnull( check_expression , replacement_value )如果check_expression為空,則返回replacement_value的值,不為空,就返回check_expression字符操作类 
5,sp_addtype自定義數據類型
例如:exec sp_addtype birthday, datetime, 'null'
6,set nocount {on|off}
使返回的结果中不包含有关受 transact-sql 语句影响的行数的信息。如果存储过程中包含的一些语句并不返回许多实际的数据,则该设置由于大量减少了网络流量,因此可显著提高性能。set nocount 设置是在执行或运行时设置,而不是在分析时设置。set nocount 为 on 时,不返回计数(表示受 transact-sql 语句影响的行数)。

set nocount 
为 off 时,返回计数
常识
 
在sql查询中:from后最多可以跟多少张表或视图:256在sql语句中出现 order by,查询时,先排序,后取在sql中,一个字段的最大容量是8000,而对于nvarchar(4000),由于nvarchar是unicode码。  
    
sqlserver2000
同步复制技术实现步骤
一、 预备工作
1.发布服务器,订阅服务器都创建一个同名的windows用户,并设置相同的密码,做为发布快照文件夹的有效访问用户--管理工具--计算机管理--用户和组--右键用户--新建用户--建立一个隶属于administrator组的登陆windows的用户(synuser)2.在发布服务器上,新建一个共享目录,做为发布的快照文件的存放目录,操作:
我的电脑--d:\ 新建一个目录,名为: pub
--右键这个新建的目录--属性--共享--选择"共享该文件夹"--通过"权限"按纽来设置具体的用户权限,保证第一步中创建的用户(synuser) 具有对该文件夹的所有权限
 
--确定3.设置sql代理(sqlserveragent)服务的启动用户(发布/订阅服务器均做此设置)
开始--程序--管理工具--服务
--右键sqlserveragent--属性--登陆--选择"此账户"--输入或者选择第一步中创建的windows登录用户名(synuser)--"密码"中输入该用户的密码4.设置sql server身份验证模式,解决连接时的权限问题(发布/订阅服务器均做此设置)
企业管理器
--右键sql实例--属性--安全性--身份验证--选择"sql server 和 windows"--确定5.在发布服务器和订阅服务器上互相注册
企业管理器
--右键sql server组--新建sql server注册...--下一步--可用的服务器中,输入你要注册的远程服务器名 --添加--下一步--连接使用,选择第二个"sql server身份验证"--下一步--输入用户名和密码(synuser)--下一步--选择sql server组,也可以创建一个新组--下一步--完成6.对于只能用ip,不能用计算机名的,为其注册服务器别名(此步在实施中没用到) (在连接端配置,比如,在订阅服务器上配置的话,服务器名称中输入的是发布服务器的ip)
开始--程序--microsoft sql server--客户端网络实用工具
--别名--添加--网络库选择"tcp/ip"--服务器别名输入sql服务器名--连接参数--服务器名称中输入sql服务器ip地址--如果你修改了sql的端口,取消选择"动态决定端口",并输入对应的端口号
二、 正式配置
1、配置发布服务器
打开企业管理器,在发布服务器(b、c、d)上执行以下步骤:
(1) 从[工具]下拉菜单的[复制]子菜单中选择[配置发布、订阅服务器和分发]出现配置发布和分发向导(2) [下一步] 选择分发服务器 可以选择把发布服务器自己作为分发服务器或者其他sql的服务器(选择自己)(3) [下一步] 设置快照文件夹
采用默认\\servername\pub
(4) [下一步] 自定义配置
可以选择:是,让我设置分发数据库属性启用发布服务器或设置发布设置
否,使用下列默认设置(推荐)
(5) [下一步] 设置分发数据库名称和位置 采用默认值(6) [下一步] 启用发布服务器 选择作为发布的服务器(7) [下一步] 选择需要发布的数据库和发布类型(8) [下一步] 选择注册订阅服务器(9) [下一步] 完成配置2、创建出版物
发布服务器b、c、d上
(1)从[工具]菜单的[复制]子菜单中选择[创建和管理发布]命令(2)选择要创建出版物的数据库,然后单击[创建发布](3)在[创建发布向导]的提示对话框中单击[下一步]系统就会弹出一个对话框。对话框上的内容是复制的三个类型。我们现在选第一个也就是默认的快照发布(其他两个大家可以去看看帮助)(4)单击[下一步]系统要求指定可以订阅该发布的数据库服务器类型,sqlserver允许在不同的数据库如 oracle或access之间进行数据复制。
但是在这里我们选择运行"sql server 2000"的数据库服务器
(5)单击[下一步]系统就弹出一个定义文章的对话框也就是选择要出版的表
注意: 如果前面选择了事务发布 则再这一步中只能选择带有主键的表
(6)选择发布名称和描述(7)自定义发布属性 向导提供的选择:
是 我将自定义数据筛选,启用匿名订阅和或其他自定义属性
否 根据指定方式创建发布 (建议采用自定义的方式)
(8)[下一步] 选择筛选发布的方式(9)[下一步] 可以选择是否允许匿名订阅1)如果选择署名订阅,则需要在发布服务器上添加订阅服务器
方法: [工具]->[复制]->[配置发布、订阅服务器和分发的属性]->[订阅服务器] 中添加
否则在订阅服务器上请求订阅时会出现的提示:改发布不允许匿名订阅
如果仍然需要匿名订阅则用以下解决办法
[企业管理器]->[复制]->[发布内容]->[属性]->[订阅选项] 选择允许匿名请求订阅2)如果选择匿名订阅,则配置订阅服务器时不会出现以上提示(10)[下一步] 设置快照 代理程序调度(11)[下一步] 完成配置
当完成出版物的创建后创建出版物的数据库也就变成了一个共享数据库
有数据
srv1.库名..author有字段:id,name,phone, srv2.库名..author有字段:id,name,telphone,adress 
 
要求:
srv1.库名..author增加记录则srv1.库名..author记录增加srv1.库名..author的phone字段更新,则srv1.库名..author对应字段telphone更新
--*/ 
 
--大致的处理步骤--1.在 srv1 上创建连接服务器,以便在 srv1 中操作 srv2,实现同步exec sp_addlinkedserver 'srv2','','sqloledb','srv2的sql实例名或ip' exec sp_addlinkedsrvlogin 'srv2','false',null,'用户名','密码' 
go
--2.在 srv1 和 srv2 这两台电脑中,启动 msdtc(分布式事务处理服务),并且设置为自动启动
。我的电脑--控制面板--管理工具--服务--右键 distributed transaction coordinator--属性--启动--并将启动类型设置为自动启动
go 
 
 
--然后创建一个作业定时调用上面的同步处理存储过程就行了
 
企业管理器
--管理--sql server代理--右键作业--新建作业--"常规"项中输入作业名称--"步骤"项--新建--"步骤名"中输入步骤名--"类型"中选择"transact-sql 脚本(tsql)" --"数据库"选择执行命令的数据库--"命令"中输入要执行的语句: exec p_process --确定--"调度"项--新建调度--"名称"中输入调度名称--"调度类型"中选择你的作业执行安排--如果选择"反复出现" --点"更改"来设置你的时间安排
 
 
然后将sql agent服务启动,并设置为自动启动,否则你的作业不会被执行
 
设置方法: 
我的电脑--控制面板--管理工具--服务--右键 sqlserveragent--属性--启动类型--选择"自动启动"--确定. 
 
 
--3.实现同步处理的方法2,定时同步
 
--在srv1中创建如下的同步处理存储过程
create proc p_process 
as 
--更新修改过的数据
update b set name=i.name,telphone=i.telphone 
from srv2.库名.dbo.author b,author i 
where b.id=i.id and
(b.name <> i.name or b.telphone <> i.telphone) 
 
--插入新增的数据insert srv2.库名.dbo.author(id,name,telphone) 
select id,name,telphone from author i 
where not exists( 
select * from srv2.库名.dbo.author where id=i.id) 
 
--删除已经删除的数据(如果需要的话) 
delete b 
from srv2.库名.dbo.author b 
where not exists( 
select * from author where id=b.id)
go

 ---------------------------

c#数据库的项目---管理系统

 

 

wpf

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

   

 

   

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网