1. 程式人生 > >步步為營-65-線程小例子

步步為營-65-線程小例子

res rgs int alt ntc gen orm read win

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(); } } }
View Code

技術分享

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 = xh; }), (int)(currentCount/count)*100
                                );
                            fsWrite.Write(bs,0,len);
                        }
                    }
                }
            });
            //02 設置為後臺線程 
            th.IsBackground = true;
            //03 啟動
            th.Start();
        }
    }
}
View Code

技術分享

3

步步為營-65-線程小例子