In Multithread programming, these are two methods that help create another Thread
1. ThreadStart This is a method that creates a new thread whose parameter is a ThreadStart delegate
2. ParameterizedThreadStart This is a method that creates a new Thread whose parameter is a ParameterizedThreadStart delegate
See general examples
1. ThreadStart This is a method that creates a new thread whose parameter is a ThreadStart delegate
Thread t1 = new Thread(new ThreadStart(Multi));
where Multi is a method pointer with no parameters 2. ParameterizedThreadStart This is a method that creates a new Thread whose parameter is a ParameterizedThreadStart delegate
Thread t2 = new Thread(new ParameterizedThreadStart(Add));
t2.Start(ap); // Start running Thread and pass parameters
where Add is a method pointer containing parameters See general examples
using System;
using System.Threading;
namespace AddWithThread
{
class AddParams
{
public int a, b;
public AddParams(int num1, int num2)
{
a = num1;
b = num2;
}
}
class Program
{
static void Multi()
{
//Xem id của thread khởi tạo bằng ThreadStart
Console.WriteLine("ID of thread in Multi(): {0}", Environment.CurrentManagedThreadId);
}
static void Add(object? data)
{
if(data is AddParams ap)
{
//View the id of the thread initiated with ParameterizedThreadStart
Console.WriteLine("ID of thread in Add(): {0}",Environment.CurrentManagedThreadId);
//See results
Console.WriteLine("{0} + {1} is {2}", ap.a, ap.b, ap.a + ap.b);
}
}
public static void Main(string[] args)
{
// View main thread id
Console.WriteLine("ID of thread in Main(): {0}",Environment.CurrentManagedThreadId);
//Initialize ThreadStart
Thread t1 = new Thread(new ThreadStart(Multi));
t1.Start(); // Bắt đầu chạy Thread
//Initialize ParameterizedThreadStart
AddParams ap = new AddParams(10, 10);
Thread t2 = new Thread(new ParameterizedThreadStart(Add));
t2.Start(ap); //Start running Thread and pass parameters
Thread.Sleep(5);
Console.ReadLine();
}
}
}
Result:
Post a Comment