C#笔记 入门 1 2 3 4 5 6 7 8 9 10 11 12 13 14 using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace Test { class Program { static void Main (string [] args ) { string s=string .Empty; Console.Title="Title" ; Console.WriteLine("Hello World!" ); s=Console.ReadLine(); } } }
Char类常用方法 IsDigit IsLetter IsLetterOrDigit IsLower IsNumber IsPunctuation IsSeparator IsUpper IsWhiteSpace Parse ToLower ToString ToUpper TryParse
多级转义 1 Console.WriteLine(@"..." );
动态常量 1 2 3 4 5 6 7 class Program { readonly int Price; Programe(){ Price=368 ; } static void Main (string [] args ) {} }
Convert类常用方法 ToBoolean ToByte ToChar ToDateTime ToDecimal ToDouble ToInt32 ToInt64 ToSByte ToSingle ToString ToUInt32 ToUInt64
数组 一维数组 1 2 3 4 int [] arr=new int [5 ];for (int i=0 ;i<arr.Length;i++){ arr[i]=i+1 ; }
二维数组 以下两种方法均可。
1 2 3 4 5 int [,] a=new int [2 ,4 ];int [][] a=new int [2 ][];a[0 ]=new int [2 ]; a[1 ]=new int [3 ];
foreach 1 2 3 4 string [] roles={"a" ,"b" ,...};foreach (string role in roles){ Console.WriteLine(role+" " ); }
List 1 2 List<string > list=new List<string >(); list.Add("..." );
Sort 从小到大,只能为一维数组。
1 2 3 4 5 6 7 8 9 public static void Sort (Array array )public static void Sort (Array array,int index,int length )int [] arr =new int []{3 ,9 ,27 ,6 ,18 ,12 ,21 ,15 };Array.Sort(arr);
Reverse 用法同上。
字符串 IndexOf 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public int IndexOf (char value )public int IndexOf (string value )public int IndexOf (char value ,int startIndex )public int IndexOf (string value ,int startIndex )public int IndexOf (char value ,int startIndex,int count )public int IndexOf (string value ,int startIndex,int count )string str ="We are the world" ;int size=str.IndexOf('e' ); string str="We are the world" ;int firstIndex=str.IndexOf("r" );int secondIndex=str.IndexOf("r" ,firstIndex+1 );int thirdIndex=str.IndexOf("r" ,secondIndex+1 );
LastIndexOf 用法同上。
StartsWith 1 2 3 4 5 6 7 8 9 10 public bool StartsWith (string value )public bool StartsWith (string value ,bool ignoreCase,CultureInfo culture )string str ="Keep on ..." ;bool result=str.StartsWith("keep" ,true ,null );
Equals 1 2 3 4 5 6 7 public bool Equals (string value )public static bool Equals (string a,string b )string pwd =Console.ReadLine();if (pwd.Equals("aaa" )){ }
ToUpper/ToLower 1 2 Console.WriteLine(str.ToUpper()); Console.WriteLine(str.ToLower());
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 Console.WriteLine(string .Format("aaa{0:D}" ,1234 )); Console.WriteLine(string .Format("aaa{0:C}" ,5201 )); Console.WriteLine(string .Format("aaa{0:E}" ,120000.1 )); Console.WriteLine(string .Format("aaa{0:N0}" ,12800 )); Console.WriteLine(string .Format("aaa{0:F2}" ,Math.PI)); Console.WriteLine(string .Format("aaa{0:X4}" ,33 )); Console.WriteLine(string .Format("aaa{0:P0}" ,0.01 )) int money=1298 ;Console.WriteLine(money.ToString("C" )); DateTime strDate=DateTime.Now; Console.WriteLine(string .Format("{0:d}" ,strDate)); Console.WriteLine(string .Format("{0:D}" ,strDate)); Console.WriteLine(string .Format("{0:f}" ,strDate)); Console.WriteLine(string .Format("{0:F}" ,strDate)); Console.WriteLine(string .Format("{0:g}" ,strDate)); Console.WriteLine(string .Format("{0:G}" ,strDate)); Console.WriteLine(string .Format("{0:M}" ,strDate)); Console.WriteLine(string .Format("{0:t}" ,strDate)); Console.WriteLine(string .Format("{0:T}" ,strDate)); Console.WriteLine(string .Format("{0:Y}" ,strDate)); DateTime dTime=DateTime.Now; Console.WriteLine(dTime.ToString("Y" ));
Substring 1 2 3 4 5 6 public string Substring (int startIndex ) ;public string Substring (int stratIndex,int length ) ;string strFile="Program.cs" ;string strFileName=strFile.Substring(0 ,strFile.IndexOf('.' ));string strExtension=strFile.Substring(strFile.IndexOf('.' ));
Split 1 2 3 4 5 char [] separator={',' };string [] splitStrings=str.Split(separator,StringSplitOptions.RemoveEmptyEntries);for (i=0 ;i<splitStirng.Length;i++){ Console.WriteLine(splitStirng[i]); }
Trim 1 string shortStr=str.Trim();
Replace 1 2 3 string strOld="..." ;string strNew1=strOld.Replace(',' ,'*' );string strNew2=strOld.Replace("one" ,"One" );
StringBuilder 1 2 3 4 5 6 7 8 StringBuilder SBuilder=new StringBuilder("..." ); int Num=368 ;SBuilder.Append("..." ); SBuilder.AppendFormat("{0:C0}" ,Num); SBuilder.Insert(0 ,"..." ); SBuilder.Remove(14 ,SBuilder.Length-14 ); SBuilder.Replace("..." ,"..." ); Console.WriteLine(SBuilder);
OOP 类的属性 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 class Program { private int age; public int Age{ get { return age; } set { if (value >0 &&value <70 ) age=value ; else Console.WriteLine("非法" ); } } public string FullName{ get ;set ; } static void Main (string [] args ) { Program p=new Program(); while (true ) p.Age=Convert.ToInt16(Console.ReadLine()); } }
构造/析构函数 1 2 3 4 5 6 7 8 9 10 11 12 13 public class Program { static Program () { Console.WriteLine("a" ); } private Program () { Console.WriteLine("b" ); } static void Main (string [] args ) { Program p1=new Program(); Program p2=new Program(); } ~Program(){} }
方法参数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 class Program { private int Add (int x,int y ) { x=x+y; return x; } private int Add (ref int x,int y ) { x=x+y; return x; } private int Add (int x,int y,out int z ) { z=x+y; return z; } private int Add (params int [] x ) { int result=0 ; for (int i=0 ;i<x.Length;i++) result+=x[i]; return result; } static void Main (string [] args ) { Program pro=new Program(); int x=30 ,y=40 ,z; Console.WriteLine(pro.Add(x,y)); Console.WriteLine(pro.Add(ref x,y)); Console.WriteLine(pro.Add(x,y,out z)); Console.WriteLine(pro.Add(20 ,30 ,40 ,50 ,60 )); return ; } }
继承/重写 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 class Computer { public string sayHello () { return "a" ; } } class Pad :Computer { public new string sayHello () { return base .sayHello()+"b" ; } } class Program { static void Main (string [] args ) { Computer pc=new Computer(); Pad ipad=new Pad(); } }
虚方法及其重写 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 class Vehicle { string name; private int value ; public string Name{ get {return name;} set {name=value ;} } public virtual void Move () { Console.WriteLine("{0}a" ,Name); } } class Train :Vehicle { public override void Move () { Console.WriteLine("{0}b" ,Name); } } class Car :Vehicle { public override void Move () { Console.WriteLine("{0}c" ,Name); } } class Program { static void Main (string [] args ) { Vehicle vehicle=new Vehicle(); Train train=new Train(); Car car=new Car(); vehicle[] vehicles={vehicle,train,car}; vehicle.Name="1" ; train.Name="2" ; car.Name="3" ; vehicle[0 ].Move(); vehicle[1 ].Move(); vehicle[2 ].Move(); return ; } }
抽象/接口 1 2 3 4 5 6 7 8 9 10 public abstract class Market { public string Name{get ;set ;} public string Goods{get ;set ;} public abstract void Shop () ; } interface Information { string Code{get ;set ;} string Name{get ;set ;} void ShowInfo () ; }
比较项
抽象类
接口
方法
可以有非抽象方法
所有方法都是抽象方法
属性
属性中可以有非静态变量
所有属性都是静态变量
构造函数
有构造函数
没有构造函数
继承
一个类只能继承一个父类
一个类可以同时实现多个接口
被继承
一个类可以被多个子类继承
一个接口可以同时继承多个接口
Windows控件 窗体 1 2 3 4 5 Application.Run(new Form1()); Form2 frm2=new Form2(); frm2.Show(); this .Hide();
MDI窗体 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 Form2 frm2=new Form2(); frm2.MdiParent=this ; frm2.Show(); Form3 frm3=new Form3(); frm3.MdiParent=this ; frm3.Show(); LayoutMdi(MdiLayout.TileHorizontal); LayoutMdi(MdiLayout.TileVertical); LayoutMdi(MdiLayout.Cascade); FormChild formChild=new ForChild(); bool isOpened=false ;foreach (Form form in this .MdiChildren){ if (formChild.Name==form.Name){ formChild.Activate(); formChild.StartPosition=FormStartPosition.CenterParent; formChild.WindowState=FormWindowState.Normal; isOpened=true ; formChild.Dispose(); break ; } } if (!isOpened){ formChild.MdiParent=this ; formChild.Show(); }
Label 1 2 label1.Text="..." ; label1.Visible=true ;
TextBox 1 2 3 4 textBox1.ReadOnly=true ; textBox1.PasswordChar='*' ; textBox1.Multiline=true ; label1.Text=textBox1.Text;
1 2 3 4 5 radioButton1_CheckedChanged(...) if (radioButton1.Checked){ }
CheckBox 1 2 3 4 5 6 7 8 9 10 string strPop="" ;foreach (Control ctrl in this .Controls){ if (ctrl.GetType().Name=='CheckBox' ){ CheckBox cBox=(CheckBox)ctrl; if (cBox.Checked){ strPop+="\n" +cBox.Text; } } } MessageBox.Show(strPop);
RichTextBox 1 2 3 4 5 6 7 8 9 10 11 12 richTextBox1.Multiline=true ; richTextBox1.ScrollBar=RichTextBoxScrollBars.Vertical; richTextBox1.SelectionFont=new Font("楷体" ,12 ,FontStyle.Bold); richTextBox1.SelectionColor=System.Drawing.Color.Red; richTextBox1.SelectionBullet=true ; private void Form1_Load (object sender,EventArgs e ) { richTextBox1.Text="http://www.baidu.com" ; } private void richTextbox1_LinkClicked (object sender,LinkClickedEventArgs e ) { System.Diagnostics.Process.Start(e.LinkText); }
ComboBox 1 2 3 4 5 6 7 8 9 10 private void Form1_Load (object sender,EventArgs e ) { combox1.DropDownStyle=ComboBoxStyle.DropDownList; string [] str=new string []{"a" ,"b" ,"c" ,"d" ,"e" ,"f" }; comboBox1.DataSource=str; comboBox1.SelectedIndex=0 ; return ; } private void comboBox1_SelectedIndexChanged (object sender,EventArgs e ) { label2.Text=comboBox1.SelectedItem; }
ListBox 1 2 3 4 5 listBox1.Items.Add("aaa" ); listBox1.Items.Remove("aaa" ); listBox1.HorizontalScrollbar=true ; listBox1.ScrollAlwaysVisible=true ; listBox1.SelectionMode=SelectionMode.MultiExtended;
GroupBox
ListView 1 2 3 4 5 6 7 8 9 10 11 12 13 listView1.Items.Add("aaa" ); listView1.Items.RemoveAt(listView1.SelectedItems[0 ].Index); listView1.Items.Clear(); listView1.Items[2 ].Selected=true ; listView1.LargeImageList=imageList1; listView1.SmallImageList=imageList1; listView1.Items[0 ].ImageIndex=0 ; listView1.Items[1 ].ImageIndex=1 ; listView1.Groups.Add(new ListViewGroup("aaa" ,_HorizontalAlignment.Left)); listView1.Groups.RemoveAt(1 ); listView1.Groups.Clear(); listView1.Items[0 ].Group=listView1.Groups[0 ];
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 private void Form1_Load (object sender,EventArgs e ) { treeView1.ContextMenuStrip=contextMenuStrip1; TreeNode TopNode=treeView1.Nodes.Add("a" ); TreeNode ParentNode1=new TreeNode("b" ); TopNode.Nodes.Add(ParentNode1); TreeNode ChildNode1=new TreeNode("c" ); ParentNode1.Nodes.Add(ChildNode1); imageList1.Images.Add(Image.FromFile("1.png" )); imageList1.Images.Add(Image.FromFile("2.png" )); treeView1.ImageList=imageList1; imageList1.ImageSize=new Size(16 ,16 ); treeView1.ImageIndex=0 ; treeView1.SelectedImageIndex=1 ; return ; } private void treeView1_AfterSelect (object sender,TreeViewEventArgs e ) { label1.Text=e.Node.Text; } private void 全部展开ToolStripMenuItem_Click(object sender,EventArgs e){ treeView1.ExpandAll(); } private void 全部折叠ToolStripMenuItem_Click(object sender,EventArgs e){ treeView1.CollapseAll(); }
Timer 1 2 3 4 5 6 7 8 9 10 11 if (timer1.Enabled){ } timer1.Interval=1 ; timer1.Start(); timer1.Stop(); private void timer1_Tick (object sender,EventArgs e ) { Random rnd=new Random(); label1.Text=rnd.Next(1 ,33 ).ToString("00" ); return ; }
MessageBox 1 DialogResult ret=MessageBox.Show("aaa" ,"bbb" ,MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
MessageBoxButtons枚举值:MessageBoxButtons.OK MessageBoxButtons.OKCancel MessageBoxButtons.AbortRetryIgnore MessageBoxButtons.YesNoCancel MessageBoxButtons.YesNo MessageBoxButtons.RetryCancel
MessageBoxIcon枚举值:MessageBoxIcon.None MessageBoxIcon.Question MessageBoxIcon.Exclaimation MessageBoxIcon.Asterisk MessageBoxIcon.Stop MessageBoxIcon.Error MessageBoxIcon.Warning MessageBoxIcon.Information
DialogResult枚举值:DialogResult.None DialogResult.OK DialogResult.Cancel DialogResult.Abort DialogResult.Retry DialogResult.Ignore DialogResult.Yes DialogResult.No
OpenFileDialog 1 2 3 4 openFileDialog1.InitialDirectory="C:\\" ; openFileDialog1.Filter="bmp文件(*.bmp)|*.bmp|gir文件(*.gif)|*.gif" ; openFileDialog1.ShowDialog(); string strName=openFileDialog1.Filename;
其他属性
描述
AddExtension
用户省略扩展名时是否在文件名中添加扩展名。
DefaultExt
默认文件扩展名。
FileNames
获取所有选定文件的文件名。
Multiselect
是否允许选择多个文件。
RestoreDirectory
对话框关闭前是否还原当前目录。
其他方法
描述
OpenFile
以只读模式打开选择的文件。
SaveFileDialog 同上。
FolderBrowserDialog 1 2 3 4 folderBrowserDialog1.ShowNewFolderButton=false ; if (folderBrowserDialog1.ShowDialog()==DialogResult.OK){ textBox1.Text=folderBrowserDialog1.SelectedPath; }
其他属性
说明
Description
显示的说明文本。
RootFolder
开始浏览的根文件夹。
I/O
File Exists 确定指定的文件是否存在。权限不够也返回false。
1 bool ret=File.Exists("C:\\Test.txt" );
Create 创建文件。
1 File.Create("C:\\Test.txt" );
Copy 1 File.Copy("C:\\Test.txt" ,"D:\\Test.txt" );
Move 1 File.Move("C:\\Test.txt" ,"D:\\Test.txt" );
Delete 1 File.Delete("C:\\Test.txt" );
FileInfo Exists 1 2 3 4 FileInfo finfo=new FileInfo("C:\\Test.txt" ); if (finfo.Exists){ }
Create 1 2 FileInfo finfo=new FileInfo("C:\\Test.txt" ); finfo.Create();
CopyTo 1 2 FileInfo finfo=new FileInfo("C:\\Test.txt" ); finfo.CopyTo("D:\\Test.txt" ,true );
MoveTo 1 2 FileInfo finfo=new FileInfo("C:\\Test.txt" ); finfo.MoveTo("D:\\Test.txt" );
Delete 1 2 FileInfo finfo=new FileInfo("C:\\Test.txt" ); finfo.Delete();
详细信息 1 2 3 4 5 6 7 8 9 10 11 12 13 14 private void button1_Click (object sender,EventArgs e ) { if (openFileDialog1.ShowDialog()==DialogResult.OK){ textBox1.Text=openFileDialog1.Filename; FileInfo finfo=new FileInfo(textBox1.Text); string strCTime=finfo.CreateionTime.ToShortDateString(); string strLATime=finfo.LastAccessTime.ToShortDateString(); string strLWTime=finfo.LastWriteTime.ToShortDateString(); string strName=finfo.Name; string strFName=finfo.FullName; string strDName=finfo.DirectoryName; string strISRead=finfo.IsReadOnly.ToString(); long lgLength=finfo.Length; } }
Directory Exists 1 Directory.Exists("C:\\Test" );
CreateDirectory 1 DirectoryInfo.CreateDirectory("C:\\Test" )
Move 只能在同一盘根目录下。
1 Directory.Move("C:\\Test" ,"C:\\aaa\\Test" );
Delete 1 Directory.Delete("C:\\Test" );
DirectoryInfo Exists 1 2 3 4 DirectoryInfo dinfo=new DirectoryInfo("C:\\Test" ); if (dinfo.Exists){ }
CreateDirectory 1 2 DirectoryInfo dinfo=new DirectoryInfo("C:\\Test" ); dinfo.Create();
MoveTo 只能在同一盘根目录下。
1 2 DirectoryInfo dinfo=new DirectoryInfo("C:\\Test" ); dinfo.MoveTo("C:\\aaa\\Test" );
Delete 1 2 DirectoryInfo dinfo=new DirectoryInfo("C:\\Test" ); dinfo.Delete();
FileSystemInfo 1 2 3 4 5 6 7 8 9 10 11 12 DirectoryInfo dinfo=new DirectoryInfo("..." ); FileSystemInfo[] fsinfos=dinfo.GetFileSystemInfos(); foreach (FileSystemInfo fsinfo in fsinfos){ if (fsinfo is DirecotryInfo){ DirectoryInfo dirinfo=new DirectoryInfo(fsinfo.Fullname); } else { FileInfo finfo=new FileInfo(fsinfo.FullName); } }
StreamWriter/StreamReader 1 2 3 4 5 6 7 StreamWriter sw=new StreamWriter("..." ,true ); sw.WriteLine("..." ); sw.Close(); StreamReader sr=new StreamReader("..." ); string str=sr.ReadToEnd();sr.Close();
GDI+ Image 1 2 3 4 5 private void Form1_Paint (object sender,PaintEventArgs e ) { Image myImage=Image.FromFile("*.jpg" ); Graphics myGraphics=this .CreateGraphics(); myGraphics.DrawImage(myImage,50 ,20 ,90 ,92 ); }
Bitmap 绘制出的图像可以自动刷新。
1 2 3 4 5 Bitmap bmp=new Bitmap(120 ,80 ); Graphics g=Graphics.FromImage(bmp); Pen myPen=new Pen(Color.Green,3 ); g.DrawEllipse(myPen,50 ,10 ,120 ,80 ); this .BackgroundImage=bmp;
异常处理 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 static int MyInt (string a,string b ) { int int1,int2,num; try { int1=int .Parse(a); int2=int .Parse(b); if (int2==0 ){ throw new DivideByZeroException(); } num=int1/int2; return num; } catch (DivideByZeroException de){ Console.WriteLine(de.Message); } catch (Exception ex){ Console.WriteLine(ex); } finally { return 0 ; } }
Socket
Dns/IPAddress/IPHostEntry 1 2 3 4 5 6 7 8 9 10 11 12 13 string localname=Dns.GetHostName();IPAddress[] ips=Dns.GetHostAddresses(localname); foreach (IPAddress ip in ips) if (!ip.IsIPv6SiteLocal) localip=ip.ToString(); try { IPHostEntry host=Dns.GetHostEntry("192.168.1.50" ); name=host.HostName.ToString(); } catch (Exception ex{ MessageBox.Show(ex.Message); }
TcpClient/TcpListener实战 Server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 namespace Server { class Program { static void Main () { int port=888 ; TcpClient tcpClient; IPAddress[] serverIP=Dns.GetHostAddresses("127.0.0.1" ); IPAddress localAddress=serverIP[0 ]; TcpListener tcpListener=new TcpListener(localAddress,port); tcpListener.Start(); while (true ){ try { tcpClient=tcpListener.AcceptTcpClient(); NetworkStream networkStream=tcpClient.GetStream(); BinaryReader reader=new BinaryReader(networkStream); BinaryWriter writer=new BinaryWriter(networkStream); while (true ){ try { string strReader=reader.ReadString(); string [] strReaders=strReader.Split(new char []{' ' }); writer.Write("..." ); } catch { break ; } } } catch { break ; } } } } }
Client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 namespace Client { class Program { static void Main (string [] args ) { TcpClient tcpClient=new TcpClient(); tcpClient.Connect("127.0.0.1" ,888 ); if (tcpClient!=null ){ NetworkStream networkStream=tcpClient.GetStream(); BinaryReader reader=new BinaryReader(networkStream); BinaryWriter writer=new BinaryWriter(networkStream); string localip="127.0.0.1" ; IPAddress[] ips=Dns.GetHostAddresses(Dns.GetHostName()); foreach (IPAddress ip in ips) if (!ip.IsIPv6SiteLocal) localip=ip.ToString(); writer.Write(localip+" ..." ); while (true ){ try { string strReader=reader.ReadString(); if (strReader!=null ) Console.WriteLine(strReader); } catch { break ; } } } } } }
UdpClient Server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 namespace Server { class Program { static UdpClient udp=new UdpClient(); static void Main (string [] args ) { udp.Connect("127.0.0.1" ,888 ); while (true ){ Thread thread=new Thread(()=>{ try { Byte[] sendBytes=Encoding.Default.GetBytes("(" +DateTime.Now.ToLongTimeString()+")..." ); udp.Send(sendBytes,sendByes.Length); } catch (Exception ex){ Console.WriteLine(ex.Message); } }); thread.Start(); Thread.Sleep(1000 ); } } } }
Client:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 namespace Client { public partial class Form1 :Form { public Form1 () { InitializeComponent(); CheckForIllegalCrossThreadCalls=false ; } bool flag=true ; UdpClient udp; Thread thread; private void button1_Click (object sender,EventArgs e ) { udp=new UdpClient(888 ); flag=true ; IPEndPoint ipendpoint=new IPEndPoint(IPAddress.Any,888 ); thread=new Thread((=>{ while (flag){ try { if (udp.Available<=0 ) continue ; if (udp.Client==null ) return ; byte [] bytes=udp.Recieve(ref ipendpoint); string str=Encoding.Default.GetString(bytes); } catch (Exception ex){ MessageBox.Show(ex.Message); } Thread.Sleep(1000 ); } })); thread.Start(); } private void button2_Click (object sender,EventArgs e ) { flag=false ; if (thread.ThreadState==ThreadState.Running) thread.Abort(); udp.Close(); } } }
Thread
Start 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 public partial class Form1 :Form { public Form1 () { InitializeComponent(); CheckForIllegalCrossThreadCalls=false ; } void Roll () { Thread.Sleep(1000 ); th2.Join(); lock (this ){ } Monitor.Enter(this ); Monitor.Exit(this ); Mutex myMutex=new Mutex(this ); myMutex.WaitOne(); myMutex.ReleaseMutex(); } private void Form1_Load (object sender,EventArgs e ) { Thread th1=new Thread(new ThreadStart(Roll)); th1.Name="线程一" ; th1.Priority=ThreadPriority.Lowest; th1.Start(); th1.Suspend(); th1.Resume(); } private void Form1_FormClosing (object sender,EventArgs e ) { if (th1.ThreadState==ThreadState.Running) th1.Abort(); } }