About thread parameters (2.0), "return value", and thread suspension
1. Thread parameters:
Sometimes you want to pass some information to the auxiliary thread. Here you need to use ParameterizedThreadStart delegate
example:
private void btRunThread_Click(object sender, EventArgs e)
{
Thread t = new Thread(new ParameterizedThreadStart(this.ThreadRun));
t.Start(100 );
}
private void ThreadRun(object o)
{
this.lbCompleted.Invoke((MethodInvoker)delegate { this.lbCompleted.Text = System.Convert.ToString(o); });
}
2. Similar functions can be roughly achieved through proxies. Example:
class Program
{
static void Main(string[] args)
{
ThreadClass tc = new ThreadClass(new MyDlg(DlgMethod));
Thread thread = new Thread(new ThreadStart(tc.ThreadRun ));
Console.WriteLine("second thread start");
thread.Start();
thread.Join();
Console.WriteLine("second thread completed");
Console.Read();
}
private static void DlgMethod(int i)
{
Console.WriteLine("Second Thread Result:{0}", i);
}
}
public delegate void MyDlg(int i);
class ThreadClass
{
private MyDlg myDlg;
public ThreadClass(MyDlg pDlg)
{
this.myDlg = pDlg;
}
public void ThreadRun()
{
int total = 0;
for (int i = 0; i < 100; i++)
{
total += i;
}
if (myDlg != null)
{
myDlg(total);
}
}
}
3. Suspension of threads:
(1) .join method
MSDN notes: While continuing to execute standard COM and SendMessage message pump processing, the calling thread is blocked until a thread terminates.
I was confused and tried it myself. It seems that after the thread calls the join method, the thread seizes all the CPU time until the thread's task is completed. Don't know if this is the case?
(2). The abort method
immediately terminates the thread
(3). Example of defining the identifier
:
class Program
{
private static bool stop;
static void Main(string[] args)
{
stop = false;
Thread t = new Thread(new ThreadStart(ThreadRun));
t.Start();
Thread.Sleep(100);
stop = true;
Console.Read();
}
static void ThreadRun()
{
while (!stop)
{
Console.WriteLine("Do Some Work...");
}
}
}
http://www.cnblogs.com/KissKnife/archive/2006/10/03/520463.html