C Method for Creating Thread with Parameters

  • 2021-11-02 02:11:22
  • OfStack

1. Creation of parameterless thread


Thread thread = new Thread(new ThreadStart(getpic));
thread.Start();
private void showmessage()
{
Console.WriteLine("hello world");
}

2. Threads with 1 parameter

With ParameterizedThreadStart, the object containing the data is passed to the thread when the System. Threading. Thread. Start (System. Object) overloaded method is called.

Note that the parameters passed can only be of type object, but you can cast them.


Thread thread = new Thread(new ParameterizedThreadStart(showmessage));
string o = "hello";
thread.Start((object)o);
private static void showmessage(object message)
{
string temp = (string)message;
Console.WriteLine(message);
}

3. Threads with two or more parameters

At this time, the methods and parameters executed by the thread can be encapsulated in a class. By instantiating this class, the methods can call properties to enjoy passing parameters.

For example, the following program wants to pass in two string variables and print them out.


public class ThreadTest
{
private string str1;
private string str2;
public ThreadTest(string a, string b)
{
str1 = a;
str2 = b;
}
public void ThreadProc()
{
Console.WriteLine(str1 + str2);
}
}
public class Example {
public static void Main() 
{
ThreadTest tt = new ThreadTest("hello ", "world");
Thread thread = new Thread(new ThreadStart(tt.ThreadProc));
thread.Start();
}
}

Related articles: