C#子线程执行完后通知主线程(转)

其实这个比较简单,子线程怎么通知主线程,就是让子线程做完了自己的事儿就去干主线程的转回去干主线程的事儿。  那么怎么让子线程去做主线程的事儿呢,我们只需要把主线程的方法传递给子线程就行了,那么传递方法就很简单了委托传值嘛

下面有一个例子,子线程干一件事情,做完了通知主线程

public class Program
    {
        //定义一个为委托
        public delegate void Entrust(string str);
        static void Main(string[] args)
        {
            Entrust callback = new Entrust(CallBack); //把方法赋值给委托
            Thread th = new Thread(Fun);
            th.IsBackground = true;
            th.Start(callback);//将委托传递到子线程中
            Console.ReadKey();
        }
        private static void Fun(object obj) {
            //注意:线程的参数是object类型
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("子线程循环操作第 {0} 次",i);
                Thread.Sleep(500);
            }
            Entrust callback = obj as Entrust;//强转为委托
            callback("我是子线程,我执行完毕了,通知主线程");
            //子线程的循环执行完了就执行主线程的方法
        }
        //主线程的方法
        private static void CallBack(string str) {
            Console.WriteLine(str);
        }
    }

上面就是一个通过委托进行向主线程传值(也就是通知主线程)的过程,上面我们是自己定义了一个委托,当然我们也可以使用.NET为我们提供的Action<>和Fun<>泛型委托来处理,就像这样

public class Program
    {
        //定义一个为委托
        public delegate void Entrust(string str);
        static void Main(string[] args)
        {
            Action<string> callback = ((string str) => { Console.WriteLine(str); });
            //Lamuda表达式
            Thread th = new Thread(Fun);
            th.IsBackground = true;
            th.Start(callback);
            Console.ReadKey();
        }
        private static void Fun(object obj) {
            for (int i = 1; i <= 10; i++)
            {
                Console.WriteLine("子线程循环操作第 {0} 次",i);
                Thread.Sleep(500);
            }
            Action<string> callback = obj as Action<string>;
            callback("我是子线程,我执行完毕了,通知主线程");
        }

    }
 //上面的Lamuda表达式也可以回城匿名函数
 //Action<string> callback = delegate(string str) { Console.WriteLine(str); };

下面是运行结果  这里写图片描述

原文地址:https://www.cnblogs.com/xihong2014/p/10925907.html