Returning a value from thread?

前端 未结 17 2166
不思量自难忘°
不思量自难忘° 2020-11-27 09:45

How do I return a value from a thread?

17条回答
  •  有刺的猬
    2020-11-27 10:21

    My favorite class, runs any method on another thread with just 2 lines of code.

    class ThreadedExecuter where T : class
    {
        public delegate void CallBackDelegate(T returnValue);
        public delegate T MethodDelegate();
        private CallBackDelegate callback;
        private MethodDelegate method;
    
        private Thread t;
    
        public ThreadedExecuter(MethodDelegate method, CallBackDelegate callback)
        {
            this.method = method;
            this.callback = callback;
            t = new Thread(this.Process);
        }
        public void Start()
        {
            t.Start();
        }
        public void Abort()
        {
            t.Abort();
            callback(null); //can be left out depending on your needs
        }
        private void Process()
        {
            T stuffReturned = method();
            callback(stuffReturned);
        }
    }
    

    usage

        void startthework()
        {
            ThreadedExecuter executer = new ThreadedExecuter(someLongFunction, longFunctionComplete);
            executer.Start();
        }
        string someLongFunction()
        {
            while(!workComplete)
                WorkWork();
            return resultOfWork;
        }
        void longFunctionComplete(string s)
        {
            PrintWorkComplete(s);
        }
    

    Beware that longFunctionComplete will NOT execute on the same thread as starthework.

    For methods that take parameters you can always use closures, or expand the class.

提交回复
热议问题