C#中给线程传值并启动

方法1:

ParameterizedThreadStart 委托+Thread.Start 方法 (Object)

        private void btnLogin_Click(object sender, RoutedEventArgs e)
        {
            ////Start the update check procedure.
            string ssid = this.txtSSID.Text;
            string username = this.txtName.Text;
            string password = this.txtPassword.Text;
//ParameterizedThreadStart 委托
            Thread loginThread = new Thread(new ParameterizedThreadStart(toLogin));
//Thread.Start 方法 (Object)
            loginThread.Start(ssid + "," + username + "," + password);
        }

        private void toLogin(object parameters)
        {
            try
            {
                string p = parameters as string;
                string s = ",";
                string[] name = p.Split(s.ToCharArray());
                string ssid = name[0];
                string username = name[1];
                string password = name[2];
                int errorCode = roaming_instance.Login(ssid, username, password);
                Debug.WriteLine("login error code:" + errorCode);
                if (AicentErrorCode.AICENT_OK == errorCode)
                {
                    //login ok
                    //add your code
                }
                else
                {
                    //failed to login
                    //add your code
                }
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine("Assert failed as login error code not match:" + ex);
            }
        }

方法2:

ThreadStart 委托+实例对象方法

using System;
using System.Threading;

class Test
{
    static void Main() 
    {
        // To start a thread using an instance method for the thread 
        // procedure, use the instance variable and method name when 
        // you create the ThreadStart delegate. Beginning in version
        // 2.0 of the .NET Framework, the explicit delegate is not
        // required.
        //
        Work w = new Work();
        w.Data = 42;
//ThreadStart 委托
        threadDelegate = new ThreadStart(w.DoMoreWork);
        newThread = new Thread(threadDelegate);
        newThread.Start();
    }
}

class Work 
{
    public int Data;
//实例对象方法
    public void DoMoreWork() 
    {
        Console.WriteLine("Instance thread procedure. Data={0}", Data); 
    }
}

/* This code example produces the following output (the order 
   of the lines might vary):

Instance thread procedure. Data=42
 */




原文地址:https://www.cnblogs.com/fifa0329/p/4536661.html