首页 > 代码库 > 步步为营-65-线程小例子
步步为营-65-线程小例子
1 摇奖机
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace _01_摇奖机 { public partial class Form1 : Form { public Form1() { InitializeComponent(); CheckForIllegalCrossThreadCalls = false; } private void button1_Click(object sender, EventArgs e) { while (true) { Random r = new Random(); label1.Text = r.Next(0, 10).ToString(); label2.Text = r.Next(0, 10).ToString(); label3.Text = r.Next(0, 10).ToString(); Thread.Sleep(1000); } } private void button2_Click(object sender, EventArgs e) { Thread th = new Thread(() => { Random r = new Random(); while (true) { label1.Text = r.Next(0, 10).ToString(); label2.Text = r.Next(0, 10).ToString(); label3.Text = r.Next(0, 10).ToString(); Thread.Sleep(1000); } }); th.IsBackground = true; th.Start(); } } }
2 拷贝文件
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace _02_文件拷贝 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //01 创建 线程 Thread th = new Thread(() => { //进行文件的读写操作 //01-01 读读读 using (FileStream fsReader = new FileStream("2015-04-14基础加强1.rar",FileMode.Open)) { //01-02 写写写 using (FileStream fsWrite = new FileStream( "a.rar",FileMode.Create)) { long count = fsReader.Length; long currentCount = 0; //设置每次读取的长度 byte[] bs = new byte[1024 * 1024]; int len; while ((len = fsReader.Read(bs,0,bs.Length))>0) { currentCount += len; progressBar1.Invoke( new Action<int>((xh) => { progressBar1.Value = http://www.mamicode.com/xh; }), (int)(currentCount/count)*100 ); fsWrite.Write(bs,0,len); } } } }); //02 设置为后台线程 th.IsBackground = true; //03 启动 th.Start(); } } }
3
步步为营-65-线程小例子
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。