将方法作为参数,传递到线程中

来源:互联网 发布:优秀的淘宝客服 编辑:程序博客网 时间:2024/05/17 07:12

        打开线程传递参数是每个初学者都会碰到的问题,尤其传递一个方法进去比较复杂。.Net不支持指针,所以传递参数需要靠委托来实现。

1,首先定义一个委托和类,其中DoSomeThing是线程要执行的方法:

    /// <summary>
    /// 定义委托
    /// </summary>
    delegate void DelegateThreadFunction ();
    /// <summary>
    /// 线程类
    /// </summary>
    class DelegateThread
    {
        //委托对象
        private DelegateThreadFunction threadFunction;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="threadFunction"></param>
        public DelegateThread(DelegateThreadFunction threadFunction)
        {
            this.threadFunction = threadFunction;
        }
        /// <summary>
        /// 执行线程函数
        /// </summary>
        public void DoSomeThing()
        {
            if (threadFunction != null )
            {
                threadFunction();
            }
        }
    }
  

2,定义要传入的方法,方法要和委托一致:

         static void dosomething()
        {
        }
 
 
3,执行线程:
        DelegateThread delegateThread = new DelegateThread(dosomething);
        Thread th = new Thread( new ThreadStart (delegateThread.DoSomeThing));
        th.Start();

转自:http://www.5x5f.com:8086/MyGroup/Discussion/Detail?GroupId=10002&DiscussionId=10471