实现线程中的参数传递

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

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

使用ParameterizedThreadStart 的示例如下:

ContractedBlock.gif ExpandedBlockStart.gif Code
class Program
{
    
static Thread thread;
    
static void Main(string[] args)
    {
        thread 
= new Thread(new ParameterizedThreadStart(ThreadProc));
        thread.Start(
1000);
    }

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

 

使用函数传递参数:

ContractedBlock.gif ExpandedBlockStart.gif Code
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();
    }
}

 

至于通过初始化类实现参数传递,就比较简单了,大家自己测试一下吧

转载于:https://www.cnblogs.com/lne818/archive/2009/06/18/1505648.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值