1. 引言
先來個比喻手法:
如果把上課的過程比作進程,那么每個學生就是一個線程,他們共享教室,即線程共享進程的內存空間。每一個時刻,只能一個學生問老師問題,老師回答完畢,輪到下一個。即線程在一個時間片內占有cpu。
這個例子容易理解多了吧?!下面馬上來看些基本概念。僅為個人理解,輕描淡寫。
2. 進程
進程是表示資源分配的基本單位,又是調度運行的基本單位。從編程的角度,也可以將進程看成一塊包含了某些資源的內存區域。
例如:當用戶打開一個txt文檔時,系統就創建一個進程,並為它分配資源。有時候打開得很慢,這是因為此時CPU運行的進程數過多,該進程需要等待調度,才能真正運行。如果再打開另外一個txt文檔時,此時在資源管理器中會發現有兩個進程,所占的內存數不一樣,是因為文檔的大小不相同。
所以我的理解是,只要是打開應用程序,就會創建進程。
在.NET框架在System.Diagnostics名稱空間中,有一個類Process,可以用來創建一個新的進程。下面用代碼來創建一個Hello.txt的記事本,運行代碼后啟動任務管理器,可以發現創建了一個記事本的進程。
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace ProcessPgr
{
class Program
{
static void Main(string[] args)
{
Process process = Process.Start("notepad.exe", "Hello.txt");//創建Hello.txt的記事本
Thread.Sleep(1000);
Console.ReadLine();
process.Kill();
}
}
}
3.線程
線程是進程中執行運算的最小單位,也是執行處理機調度的基本單位。實際上線程是輕量級的進程。那么為什么要使用線程呢?
解決方法:
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Thread thread;
public delegate void MyInvoke();
private void btnSend_Click_1(object sender, EventArgs e)
{
labMessage.Text = "正在讀取數據,請等待";
thread = new Thread(Send);
thread.IsBackground = true;
thread.Start();
}
protected void Send()
{
MyInvoke invoke = new MyInvoke(Get);
this.BeginInvoke(invoke);
}
protected void Get()
{
Thread.Sleep(3000);
txtName.Text = "TerryChan";
txtNum.Text = "07";
txtGrade.Text = "軟件工程";
}
}
}
效果:
最后總結:進程和線程的知識點不是簡單一兩句話就能說清楚,自己只是稍微有個大概了解,學習之路任重而道遠。