C# 多線程 簡單使用方法以及常用參數,
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading; //線程操作的類在這個命名空間下.
namespace C02多線程
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
//關閉控件的跨線程訪問檢查
TextBox.CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e)
{
int sum = 0;
for (int i = 0; i < 999999999; i++)
{
sum += i;
}
MessageBox.Show("ok");
}
private void button2_Click(object sender, EventArgs e)
{
//創建1個線程對象 並為這個線程對象指定要執行的方法.
Thread thread = new Thread(TestThread);
//設置線程為後台線程.
thread.IsBackground = true;
//開啟線程
thread.Start();
//線程默認情況下都是前台線程.
//要所有的前台線程退出以後 程序才會退出.
//後台線程 只要所有的前台線程結束 後台線程就會立即結束.
//進程裡默認的線程我們叫做主線程或者叫做UI線程.
//線程什麼時候結束 該線程執行的方法執行完以後 線程就自動退出.
//多個線程訪問同一資源 可能造成不同步的情況. 這個叫做 線程重入.
//th.Abort(); 強行停止線程.
//Thread.Sleep(1000);//將當前線程暫停 單位毫秒
//Thread.CurrentThread;得到當前線程的引用
//線程調用帶參數的方法
//創建1個ParameterizedThreadStart委托對象.為這個委托對象綁定方法.
//將委托對象通過構造函數傳入線程對象
//啟動線程的時候調用Start()的重載 將參數傳入.
}
//准備讓線程去調用.
private void TestThread()
{
int sum = 0;
for (int i = 0; i < 999999999; i++)
{
sum += i;
}
MessageBox.Show("ok");
}
private void CountNunm()
{
//使用lock加鎖 請聯想你上廁所的情況
lock (this)
{
for (int i = 0; i < 10000; i++)
{
int num = int.Parse(textBox1.Text.Trim());
num++;
//Thread.Sleep(500);//將當前線程暫停
// Thread.CurrentThread.Abort();
//Thread th = Thread.CurrentThread;
//th.Abort();
//if (num == 5000)
//{
// th.Abort();
//}
textBox1.Text = num.ToString();
}
}
}
Thread th;
private void button3_Click(object sender, EventArgs e)
{
th = new Thread(CountNunm);
th.Name = "哈哈線程";
th.IsBackground = true;
th.Start();
//Thread th1 = new Thread(CountNunm);
//th1.IsBackground = true;
//th1.Start();
}
private void button4_Click(object sender, EventArgs e)
{
//ThreadStart s = new ThreadStart(CountNunm);
//Thread th = new Thread(CountNunm);
ParameterizedThreadStart s = new ParameterizedThreadStart(TestThreadParsms);
Thread t = new Thread(s);
t.IsBackground = true;
t.Start("你好啊");
}
private void TestThreadParsms(object obj)
{
Console.WriteLine(obj.ToString());
}
}
}