How to call the method in thread with arguments and return some value

前端 未结 7 1814
南旧
南旧 2020-12-09 00:14

I like to call the method in thread with arguments and return some value here example

class Program
{
    static void Main()
    {
        Thread FirstThread         


        
7条回答
  •  無奈伤痛
    2020-12-09 00:53

    For some alternatives; currying:

    static ThreadStart CurryForFun(int i, int j)
    { // also needs a target object if Fun1 not static
        return () => Fun1(i, j);
    }
    
    Thread FirstThread = new Thread(CurryForFun(5, 12));
    

    or write your own capture-type (this is broadly comparable to what the compiler does for you when you use anon-methods / lambdas with captured variables, but has been implemented differently):

    class MyCaptureClass
    {
        private readonly int i, j;
        int? result;
        // only available after execution
        public int Result { get { return result.Value; } }
        public MyCaptureClass(int i, int j)
        {
            this.i = i;
            this.j = j;
        }
        public void Invoke()
        { // will also need a target object if Fun1 isn't static
            result = Fun1(i, j);
        }
    }
    ...
    MyCaptureClass capture = new MyCaptureClass(5, 12);
    Thread FirstThread = new Thread(capture.Invoke);
    // then in the future, access capture.Result
    

提交回复
热议问题