将参数传递给线程(Vc#2005)

根据MSDN

在 .NET Framework 2.0 版中,ParameterizedThreadStart 委托提供了一种简便方法,可以在调用 System.Threading.Thread.Start(System.Object) 方法重载时将包含数据的对象传递给线程。
使用 ParameterizedThreadStart 委托不是传递数据的类型安全的方法,因为 System.Threading.Thread.Start(System.Object) 方法重载接受任何对象。一种替代方法是将线程过程和数据封装在帮助器类中,并使用 ThreadStart 委托执行线程过程。

在简单情况下传递参数给线程有两种方法,一种是使用ParameterizedThreadStart 直接传递Object类型的参数。这种传递时非线程安全的。另一种方法是使用间接传递,我们可以把把数据和线程过程封装到帮助器类中或者直接在另一个不带参数的函数中调用线程过程并传递所需的参数。

使用ParameterizedThreadStart 的示例如下:

 1 class Program
 2     {
 3         static Thread thread;
 4         static void Main(string[] args)
 5         {
 6             thread = new Thread(new ParameterizedThreadStart(ThreadProc));
 7             thread.Start(1000);
 8         }
 9 
10         static void ThreadProc(object max)
11         {
12             for (int i = 0; i < (int)max; i++)
13             {
14                 Console.WriteLine(i);
15             }
16             thread.Abort();
17         }
18     }

使用函数传递参数:

class Program
    {
        
static Thread thread;
        
static void Main(string[] args)
        {
            thread 
= new Thread(new ThreadStart(Test));
            thread.Start();
        }

        
static void Test()
        {
            ThreadProc(
1000);
        }

        
static void ThreadProc(int max)
        {
            
for (int i = 0; i < max; i++)
            {
                Console.WriteLine(i);
            }
            thread.Abort();
        }
    }

使用类帮助器通过构造函数传递参数:

 1 public class Program
 2     {
 3         public static Thread thread;
 4         static void Main(string[] args)
 5         {
 6             ThreadTest tt = new ThreadTest(1000);
 7             thread = new Thread(new ThreadStart(tt.ThreadProc));
 8             thread.Start();
 9         }
10     }
11 
12     public class ThreadTest
13     {
14         int max;
15         public ThreadTest(int pMax)
16         {
17             max = pMax;
18         }
19 
20         public void ThreadProc()
21         {
22             for (int i = 0; i < max; i++)
23             {
24                 Console.WriteLine(i);
25             }
26             Program.thread.Abort();
27         }
28     }

总结起来就是直接传递与间接传递参数。

posted on 2008-04-08 16:21  费哥  阅读(1049)  评论(0编辑  收藏  举报

导航