C#建立带参数的线程

一、无参数线程的建立
Thread thread = new Thread(new ThreadStart(ShowMessage));
thread.Start();
 private void ShowMessage()
{
     Console.WriteLine("hello world");
}
二、带一个参数的线程
使用ParameterizedThreadStart,调用 System.Threading.Thread.Start(System.Object) 重载方法时将包含数据的对象传递给线程。
注意传递的参数只能是object类型,不过能够进行强制类型转换。
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);
}
三、带两个及以上参数的线程
这时候能够将线程执行的方法和参数都封装到一个类里边,经过实例化该类,方法就能够调用属性来尽享传递参数。
例如以下程序,想传入两个string变量,而后打印输出。
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();
    }
}
相关文章
相关标签/搜索