0
点赞
收藏
分享

微信扫一扫

C#利用异步和委托实现子线程更新UI(方式2)

yeamy 2022-04-04 阅读 54

UI布局如下:

声明委托:

 public delegate void  AsyncDelegate(TextBox textBox);

Form代码如下:

public partial class Form1 : Form

    {

        AsyncDelegate asyncDelegate = null;

        public Form1()

        {

            InitializeComponent();

           

            Console.WriteLine("UI初始化线程Id:" + Thread.CurrentThread.ManagedThreadId);

            asyncDelegate += AsyncStringMethod;   //委托注册方法

        }

        private void button1_Click(object sender, EventArgs e)

        {

            //委托调用

            AsyncStringMethod(this.textBox1);

        }

        private async void AsyncStringMethod(TextBox textBox)

        {

            Console.WriteLine("异步开始线程Id:"+ Thread.CurrentThread.ManagedThreadId);

            string retMsg =null;

            await Task.Run(() => {

                Console.WriteLine("异步线程Id:" + Thread.CurrentThread.ManagedThreadId);

                Interlocked.Exchange(ref retMsg, "哈咯,异步线程");

            });

            textBox.Text = retMsg;

            Console.WriteLine("异步结束线程Id:" + Thread.CurrentThread.ManagedThreadId);

        }

    }

    public delegate void  AsyncDelegate(TextBox textBox);

代码还是太简单了,不解释,注意观察线程Id的输出:

举报

相关推荐

0 条评论