线程间操作ui

using EasyNetQ.Logging;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;



namespace WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        private static IScheduler _scheduler;
        SynchronizationContext synchronizationContext = null;
        delegate void ChangeText1(string strmessage);
        private AsyncOperation operation;

        public event EventHandler labclick;
        public Form1()
        {
            InitializeComponent();
            synchronizationContext = SynchronizationContext.Current;
            operation = AsyncOperationManager.CreateOperation(null);
        }
        //public int localPort = 0;
        private void Form1_Load(object sender, EventArgs e)
        {
            IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName());
            IPAddress[] ip = ipe.AddressList;
            IPAddress iPAddress = ip[1];
           
            //IPAddress localIp = IPAddress.Parse("127.0.0.1");
            IPEndPoint iep = new IPEndPoint(ip[1], 80);
            this.label2.Text = iep.Port.ToString();
            string strip= ip.Select(o=>o).Where(o=>o.AddressFamily.ToString()== "InterNetwork").FirstOrDefault().ToString();
            this.label1.Text = strip;
            //ChangeText1 = (strmessage) => { setText1value(strmessage); };
            SettextBox2Value(Thread.CurrentThread.ManagedThreadId.ToString(),"");
            //
            //PlaySound();
            Thread thread = new Thread(new ThreadStart(GetMessage));
            thread.IsBackground = true;
            thread.Start();
            //ConsoleLogProvider logProvider = new ConsoleLogProvider();
            //logProvider.SetLogCallBack((log) =>
            //{
            //    this.rchMessage.AppendText(log);
            //});

            //MusicJob._printLogCallBack = (log) =>
            //{
            //    synchronizationContext.Send((obj) =>
            //    {
            //        this.textBox2.AppendText(log.ToString());
            //    }, null);
            //};


            //MusicJob._printLogCallBack = delegate (string log,string strThread)
            //{
            //    synchronizationContext.Post(delegate { SettextBox2Value(log.ToString(), strThread.ToString()); }, null);
            //};
            //            MusicJob._printLogCallBack = delegate (string log, string strThread)
            //            {
            //                synchronizationContext.Post(delegate { SettextBox2Value(log.ToString(), strThread.ToString()); }, null);
            //            };
            SendOrPostCallback sendOrPost = (strobj) => { SettextBox2Value("11", "22"); };//SendOrPostCallback这个需要传参
            MusicJob._printLogCallBack = (log, strthread) =>
            {
                synchronizationContext.Post(
setText1value, log);//log是给setText1value传参
            };

            //MusicJob._printLogCallBack = (log, strthread) =>
            //{
            //    this.BeginInvoke(new Func<string, string,string>(SettextBox2Value), new object[] { log, strthread });
            // 
            //};
            // SynchronizationContext线程上下文说明
            //SynchronizationContext在通讯中充当传输者的角色,实现功能就是一个线程和另外一个线程的通讯
            //那么SynchronizationContext的Send()和Post()
            //Send() 是简单的在当前线程上去调用委托来实现(同步调用)。也就是在子线程上直接调用UI线程执行,等UI线程执行完成后子线程才继续执行。
            //Post() 是在线程池上去调用委托来实现(异步调用)。这是子线程会从线程池中找一个线程去调UI线程,子线程不等待UI线程的完成而直接执行自己下面的代码。

            //LogProvider.SetCurrentLogProvider(logProvider);



        }

        public string  SettextBox2Value(string log,string strThread)
        {
            this.textBox2.AppendText(log.ToString()+ strThread+ Thread.CurrentThread.ManagedThreadId.ToString());
            return log.ToString() + strThread;
        }

        //public Form1(int localPort)
        //{
        //    this.localPort = localPort;
        //}

        /// <summary>
        /// 接收button传递过来的信息
        /// </summary>
        private void GetMessage()
        {
            UdpClient udpClient = new UdpClient(5839);
            IPEndPoint ip = null;
            // 保证一直处于接收状态
            while (true)
            {
              
                byte[] message = udpClient.Receive(ref ip);//接收
       
                string strmessage = Encoding.UTF8.GetString(message);
                //string strmessage = "ceshi111";
                synchronizationContext.Post(setText1value, strmessage);//直接使用方法ui控件更新函数
                //this.BeginInvoke(new ChangeText1(setText1value),strmessage);异步执行委托
                //this.Invoke(new ChangeText1(setText1value), strmessage);//委托很重要
                //这个方法是目前跨线程更新UI使用的主流方法,使用控件的Invoke / BegainInvoke方法,将委托转到UI线程上调用,实现线程安全的更新
               // Action<object> action = new Action<object>(setText1value);
                //this.BeginInvoke(new Action<object>(setText1value),strmessage);//异步执行委托,需要用委托绑定界面更新函数
                //this.BeginInvoke(new Action<object>(aa => this.textBox1.Text +=  aa.ToString()), strmessage);
                //异步执行委托strmessage是给BeginInvoke里的委托传参
                //使用Lambda直接把方法写在实例化代码中,不必在另一个地方定义方法,s省略方法名
                //其中=>符号代表Lambda表达式,它的左侧是参数,右侧是要返回或执行的语句。
                //参数要放在圆括号中,若只有一个参数,为了方便起见可省略圆括号。有多个参数或者没有参数时,不可省略圆括号。
                //相比匿名函数,在表达式Lambda中,方法体的花括号{ }
                //和return关键字被省略掉了。
            }
        }

        private void setText1value(object  str)
        {
            this.textBox1.Text += str.ToString();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            UdpClient uc = new UdpClient("127.0.0.1", 5839);//udp协议发送
            byte[] message = Encoding.UTF8.GetBytes("1");
            uc.Send(message, message.Length);
            uc.Close();
        }
        public string Sound { get; set; }

        private async Task PlaySound()
        {
            //synchronizationContext.Send(SettextBox2Value, Thread.CurrentThread.ManagedThreadId.ToString());
            //1.通过工厂获取一个调度器的实例
            StdSchedulerFactory factory = new StdSchedulerFactory();
            _scheduler = await factory.GetScheduler();
            await _scheduler.Start();

            //创建任务对象
            IJobDetail job = JobBuilder.Create<MusicJob>()
                .WithIdentity("job1", "group1")
                .Build();


            //创建触发器
            ITrigger trigger = TriggerBuilder.Create()
                .WithIdentity("trigger1", "group1")
                .StartNow()
                .WithCronSchedule("30 0/1 * * * ?")//每分钟的第30秒执行
                .Build();

            ////将任务加入到任务池
            await _scheduler.ScheduleJob(job, trigger);

            job = JobBuilder.Create<PrintTxtJob>()
             .WithIdentity("job2", "group1")
             .Build();

            trigger = TriggerBuilder.Create()
                .WithIdentity("trigger2", "group1")
                .StartNow()
                .WithCronSchedule("0 0/1 * * * ?")//每分钟的第0秒执行
                .Build();

            await _scheduler.ScheduleJob(job, trigger);
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}
原文地址:https://www.cnblogs.com/liuyudong0825/p/13184313.html