Multi Thread trong C#

Bạn có thể hiểu đơn giản thread là luồng dữ liệu. Thông thường 1 ứng dụng được tạo ra thường là đơn thread.
Đôi khi bạn cần xử lý 1 công việc nào đó được lập đi lại nhiều lần trong 1 thời điểm, hoặc cùng 1 lúc bạn thực hiện nhiều công việc thì bạn hãy nghĩ đến Thread

Ta có 1 ví dụ cơ bản về thread trên Console như sau:

using System;
using System.Threading;
public class Test
{
    static void Main()
    {
        ThreadStart job = new ThreadStart(ThreadJob);
        Thread thread = new Thread(job);
        thread.Start();
        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Main thread: ", i);
            Thread.Sleep(1000);
        }
 
        Console.ReadLine();
    }
    static void ThreadJob()
    {
        for (int i = 0; i < 10; i++)
        {
            Console.WriteLine("Other thread: ", i);
            Thread.Sleep(500);
        }
    }
}
Kết quả:

Như các bạn đã thấy ngoài luồng dữ liệu chính tạo ra, System.Threading.Thread còn tạo ra cho ta 1 luồng dữ liệu mới để thực hiện hàm ThreadJob()

Như vậy nếu bạn có 5 users, bạn muốn cho 5 users này cùng 1 lúc thì sao?

using System;
using System.Threading;
public class Test
{
    static void Main()
    {
 
        for (int i = 1; i <= 5; i++)
        {
            Users user = new Users(i);
            new Thread(new ThreadStart(user.Download)).Start();
        }
 
        Console.ReadLine();
    }
    public class Users
    {
        private int number;
        public Users(int number)
        {
            this.number = number;
        }
        public void Download()
        {
            for (int i = 1; i <= 3; i++)
            {
                Console.WriteLine("User  is ing file  ",this.number, i);
                Thread.Sleep(1000);
            }
        }
    }
}
Kết quả:

Nhưng khi bạn sử dụng Thread với giao diện UI, Control (Xử lý với Control trong hàm thực thi thread) thì thường xảy ra cảnh báo exception: "Cross thread operation is not valid..."
Vậy để khắc phục cảnh báo gây ra liên quan đến Control đơn giản nhất là đặt thuộc tính tĩnh:


CheckForIllegalCrossThreadCalls = false
 
Dĩ nhiên sẽ không an toàn. Ta có thể kiểm tra Invoke khi sử dụng các đối tượng này.

Ví dụ tôi có 1 Textbox và 2 hàm thực hiện chèn thêm vào textbox các dòng lần lượt:
- This is Thread 1
- This is Thread 2

Nếu các bạn viết như sau sẽ có thể gây ra lỗi "Cross thread operation is not valid..."

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
 
namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        Thread t1, t2;
         
        public Form1()
        {
            InitializeComponent();
        }
 
        private void AppendText(string s)
        {
             textBox1.AppendText(s);
             textBox1.AppendText(Environment.NewLine);
        }
 
        private void Thread1()
        {
            while (true)
            {
                AppendText("This is thread 1");
                Thread.Sleep(500);
            }
        }
 
        private void Thread2()
        {
            while (true)
            {
                AppendText("This is thread 2");
                Thread.Sleep(500);
            }
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            t1 = new Thread(Thread1);
            t2 = new Thread(Thread2);
 
            t1.Start();
            t2.Start();
        }
 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            t1.Abort();
            t2.Abort();
        }
    }
}
Vì thế ta nên kiểm tra Invoke Require khi thực hiện làm việc Thread với Control (Cụ thể đây là textbox1)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
 
namespace WindowsApplication2
{
    public partial class Form1 : Form
    {
        Thread t1, t2;
         
        public Form1()
        {
            InitializeComponent();
        }
 
        private void AppendText(string s)
        {
            if (textBox1.InvokeRequired)
            {
                textBox1.BeginInvoke(new MethodInvoker(delegate() { AppendText(s); }));
            }
            else
            {
                lock (textBox1)
                {
                    textBox1.AppendText(s);
                    textBox1.AppendText(Environment.NewLine);
                }
            }
        }
 
        private void Thread1()
        {
            while (true)
            {
                AppendText("This is thread 1");
                Thread.Sleep(500);
            }
        }
 
        private void Thread2()
        {
            while (true)
            {
                AppendText("This is thread 2");
                Thread.Sleep(500);
            }
        }
"color: rgb(20, 20, 20); font-family: Tahoma, 'Trebuchet MS', Helvetica, Arial, sans-serif; font-size: 15px; line-height: 22px;">Hi vọng qua bài viết này bạn đã hiểu cơ bản về thread và multi - thread
"color: rgb(20, 20, 20); font-family: Tahoma, 'Trebuchet MS', Helvetica, Arial, sans-serif; font-size: 15px; line-height: 22px;">Thân chào!
        private void Form1_Load(object sender, EventArgs e)
        {
            t1 = new Thread(Thread1);
            t2 = new Thread(Thread2);
 
            t1.Start();
            t2.Start();
        }
 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            t1.Abort();
            t2.Abort();
        }
    }
}