Powerpoint Templates
Page 1
TRƯỜNG ĐẠI HỌC CÔNG NGHỆ THÔNG TIN TP.HCM
KHOA HỆ THỐNG THÔNG TIN
LẬP TRÌNH CƠ SỞ DỮ LIỆU
THREAD TRONG C#
GVHD:
ThS Nguyễn Thị Kim Phụng
SVTH:
Nguyễn Trung Tín 09520684
Hồ Minh Quân 09520000
Lê Văn Hiếu 09520000
Powerpoint Templates
Page 2
NỘI DUNG
I. Giới Thiệu
II. Foreground và Background
III.Truyền dữ liệu giữa các Thread
IV. BackgroundWorker
V. Demo
THREAD TRONG C#
Powerpoint Templates
Page 3
THREAD TRONG C#
I. Giới Thiệu
Trong một chương trình C# được bắt đầu trong 1 thread đơn
Thread là một trạng thái tức thời của chương trình.
Cho phép chương trình thực hiện đồng thời nhiều
tác vụ cùng lúc
Powerpoint Templates
Page 4
THREAD TRONG C#
II. Foreground-Background
Mặc định, Thread tạo ra sẽ là Foreground
Tất cả Foreground hoàn thành Thoát ứng dụng
Xét về độ ưu tiên, Background và Foreground
ngang hàng
Dùng thuộc tính IsBackground
để xác định Background hay Foreground
Powerpoint Templates
Page 5
THREAD TRONG C#
II. Foreground-Background
static void Main(string[] args)
{
Thread t1 = new Thread(() =>
{
Thread.Sleep(1000);
Console.WriteLine("Thread t1 started");
});
// t1.IsBackground = true;
t1.Start();
Console.WriteLine("Main thread ending ");
}
Powerpoint Templates
Page 6
THREAD TRONG C#
III. Truyền dữ liệu giữa các Thread
Thực thi 1 một lambda expression
để gọi phương thức với đối số mong muốn.
static void Main()
{
Thread t = new Thread ( () => Print ("Hello from t!") );
t.Start();
}
static void Print (string message)
{
Console.WriteLine (message);
}
Powerpoint Templates
Page 7
THREAD TRONG C#
IV. BackgroundWorker
Là Component trong .NET 2.0
Namespace : System.ComponentModel
Quản lí Thread thông quan GUI
Powerpoint Templates
Page 8
THREAD TRONG C#
IV. BackgroundWorker
1. Properties
Properties Description
IsBusy Xác định Thread có làm việc hay không
WorkerReportsProgress Set hoặc Get giá trị để xác định có report
progress hay không
WorkerSupportsCancelatio
n
Set hoặc get giá trị xác định có hỗ trợ
Cancel hay không
CancelationPending Get giá trị xác định có Cancel hay không
Properties
Powerpoint Templates
Page 9
THREAD TRONG C#
IV. BackgroundWorker
2. Methods
Properties Description
CancelAsync Yêu cầu Cancel
OnDoWork Gọi sự kiện DoWork
OnProgressChanged Gọi sự kiện ProgressChanged
OnRunWorkerCommpleted Gọi sự kiện RunWorkerCompleted
PeportProgress Gọi sự kiện ProgressChanged
RunWorkerAsync Bắt đầu thực thi Background operator
Methods
Powerpoint Templates
Page 10
THREAD TRONG C#
IV. BackgroundWorker
3. Events
Properties Description
DoWork Xảy ra khi RunWorkerAsync được gọi
ProgressChanged Xảy ra khi ReportProgress được gọi
RunWorkerCompleted Xảy ra khi công việc hoàn thành, cancel,
exception
Events
Powerpoint Templates
Page 11
Gọi RunworkerAsync()
Thực thi phương
thức OnDoWork()
IsBusy=True
OnWorkerCompleted()
THREAD TRONG C#
IV. BackgroundWorker
4. Quá trình thực hiện
Powerpoint Templates
Page 12
THREAD TRONG C#
V. Demo
Powerpoint Templates
Page 13
Cảm ơn mọi người đã lắng nghe!