C#中工作线程处理完数据后将处理结果返回给UI主线程通知主线程操作界面


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading; //线程类:暂停函数

namespace Program
{
    class Program
    {
        static void Main(string[] args)
        {
            //方法1:
            //Action<Student> callback = ((Student st) => { Console.WriteLine(st.Name); });//lambda 表达式

            //方法3:
            Action<Student> callback = ShowName;

            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<Student> callback = obj as Action<Student>;

            Student st = new Student();
            st.ID = 1;
            st.Name = "Long";
            st.Age = 20;

            callback(st);
        }

        //方法2:上面的Lambda表达式也可以回城匿名函数
        private static Action<Student> callback = delegate(Student st) { Console.WriteLine(st.Name); };

        //方法3:
        private static void ShowName(Student st)
        {
            Console.WriteLine(st.Name); 
        }

    }
}

 其中,Student类的定义如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Program
{
    public class Student
    {
        public int ID;
        public string Name;
        public int Age;
    }
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM