What if you want to input a variable for a thread?
Threadstart does not support methods with parameters. Therefore, you cannot use thread to start a method with parameters ..
ThreadStart myThreadDelegate = new ThreadStart(ThreadMethod);//public delegate void ThreadStart(); u can't pass a ParameterThread myThread = new Thread(myThreadDelegate);myThread.Start(); //myThread.Start(o); Wrong!
However, in. net1.0, You can implement this through asynchronous call of delegate.
Http://www.cnblogs.com/idior/articles/100666.html
Now in. in net2.0, parameterizedthreadstart is provided. it differs from threadstart in that it can have an object-type parameter. that is to say, you can use the Thread class to start a thread and input parameters, which is very similar to Java and has good new functions.
using System;using System.Threading;namespace ParameterizedThreadStartTest{class Program{static void Main(string[] args){ParameterizedThreadStart myParameterizedThreadDelegate = new ParameterizedThreadStart(ThreadMethod);Thread myThread = new Thread(myParameterizedThreadDelegate);object o = "hello";myThread.Start(o);}private static void ThreadMethod(object o){string str = o as string;Console.WriteLine(str);}}}
There is also a new class of backgroundworker, which can be used to start the background thread and call the main thread method in time after the background computing ends. A common application is to load data in the DataGrid. since loading dataset from a database is time-consuming, you can use backgroundworker for loading. After the dataset is constructed, it is immediately bound to the DataGrid. in fact, this function can also be implemented through asynchronous call of Delegate, but it is more convenient to use backgroundworker.
//1. Instantiate a BackgroundWorker instance:BackgroundWorker myDataWorker = new BackgroundWorker();//2. Setup a DoWork delegate that does the work that you want to be done on the background thread.myDataWorker.DoWork += new DoWorkEventHandler(delegate(object o, DoWorkEventArgs workerEventArgs){workerEventArgs.Result = new XXXDAL().GetData();});//3. Setup a RunWorkerCompleted delegate that handles updating your UI with the data recieved on the background thread.myDataWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(delegate(object o, RunWorkerCompletedEventArgs workerEventArgs){DataSet data = (DataSet) workerEventArgs.Result;this.dataGrid.DataSource = data;});//4.Run your worker by calling the RunWorkerAsync() method on your BackgroundWorker instance.myDataWorker.RunWorkerAsync();