【问题标题】:Handling Parameters in Threads处理线程中的参数
【发布时间】:2011-03-13 10:14:20
【问题描述】:

我只是一个初学者。“ParameterizedThreadStart”接受单个对象作为参数。

有没有其他的委托签名可以让我

(1) 在线程上传递参数(可变数量的参数)?

(2) 支持列表等泛型参数?

【问题讨论】:

    标签: c# multithreading delegates


    【解决方案1】:

    你可以用一个对象做任何你想做的事情。只需定义一个类来包装你感兴趣的参数即可:

    class ThreadState
    {
        public ThreadState()
        {
        }
    
        public string Name
        {
            get;
            set;
        }
    
        public int Age
        {
            get;
            set;
        }
    }
    
    // ...
    
    ParameterizedThreadStart start = delegate(object objThreadState)
    {
        // cast to your actual object type
        ThreadState state = (ThreadState)objThreadState;
    
        // ... now do anything you want with it ...
    };
    

    【讨论】:

    • 或者只是传递一个对象数组。
    • 是的,你也可以传递一个数组,它更轻量级但不太“类型安全”。
    • 真的帮了我很多。谢谢。
    【解决方案2】:

    您可以使用 Delegate.BeginInvoke 和 EndInvoke 来传递您想要的任何参数

    delegate long MyFuncDelegate(int N );
    
    MyFuncDelegate cpn = new MyFuncDelegate(MyFunc); 
    
    IAsyncResult ar = cpn.BeginInvoke( 3, null, null ); 
    
    // Do some stuff 
    while( !ar.IsCompleted ) 
    { 
        // Do some stuff 
    } 
    
    // we now know that the call is 
    // complete as IsCompleted has 
    // returned true 
    long answer = cpn.EndInvoke(ar); 
    

    【讨论】:

      【解决方案3】:

      顺便说一句,使用泛型,定义具有字段的类(例如 Doer(Of T1)、Doer(Of T1, T2) 等很有用,例如V1 As T1,V2 As T2 等,以及 theAction As Action(Of T1, T2) 等以及调用 theAction(V1, V2) 和静态工厂方法的单个方法 Exec(void) 等。即使在 VS2005 中,这也使得组装一个调用具有适当参数的函数的 MethodInvoker 变得非常容易。

      【讨论】:

        猜你喜欢
        • 2018-12-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多