首先明確什么時候用多線程?
多線程是提高cpu的利用率,只有當cpu空閑時間比較多情況下,才能體現出多線程的優勢。
線程:線程是進程的組成單位。
主要步驟:
① 實例化ThreadStart對象,參數是線程將要執行的方法。
② 編寫線程將要執行的方法。
③ 實例化Thread對象,參數是剛才實例化ThreadStart的對象。
④ Thread對象啟動,
線程的例子:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace ThreadTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static int interval;
private void Form1_Load(object sender, EventArgs e)
{
interval = 1000;
Thread t = Thread.CurrentThread;
t.Name = "主要線程";
ThreadStart ts1 = new ThreadStart(ExampleMethod);
Thread t1 = new Thread(ts1);
t1.Name = "工作線程";
t1.Start();
ExampleMethod();
Console.ReadLine();
}
public void ExampleMethod() {
Thread t = Thread.CurrentThread;
string name = t.Name;
lock (this)
{
for (int i = 0; i <= 8 * interval; i++)
{
if (i % interval == 0)
{
Console.WriteLine("線程{0}計算器:{1}", name, i);
}
}
}
}
}
}
線程池:比線程在使用資源的方面更優化合理一些。
主要步驟:
① 實例化WaitCallback一個對象,參數是要執行的線程池的方法。
② 編寫線程池要執行的方法。
③ 把任務排入執行的隊列,例如ThreadPool.QueueUserWorkItem(wc1, 1);。
線程池的例子:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace Thread
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WaitCallback wc1 = new WaitCallback(ExampleMethod);
WaitCallback wc2 = new WaitCallback(ExampleMethodTwo);
ThreadPool.QueueUserWorkItem(wc1, 1);
ThreadPool.QueueUserWorkItem(wc2, 2);
Console.ReadLine();
}
public static void ExampleMethod(object status)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("線程{0}運行中", (int)status);
// Thread.Sleep(1000);
}
}
public static void ExampleMethodTwo(object status)
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("線程{0}", (int)status);
// Thread.Sleep(1000);
}
}
}
}
Timer:
這里指System.Threading.Timer,主要指在多長時間間隔執行方法體。
Timer主要步驟:
① 實例化TimerCallback對象,參數是Timer執行的方法。
② 編寫Timer執行的方法。
③ 實例化Timer對象,參數是剛才的TimerCallback對象。
Timer例子:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace MYTimerTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(timer_Elapsed), null, 0, 1000);
}
void timer_Elapsed(object sender)
{
for (int i = 0; i < 10; i++)
{
Console.Out.WriteLine(DateTime.Now + " " + DateTime.Now.Millisecond.ToString() + "timer in:");
}
}
}
}
事件
事件主要是特定的動作觸發而執行方法體。
事件源、監聽、觸發的方法體三個元素構成。