您的位置:首页 > 产品设计 > UI/UE

工作线程操作UI线程元素的方法

2017-04-26 15:20 204 查看
C#中,工作线程无法直接在线程函数中操作UI主线程中的UI对象,必须通过线程切换到UI线程去执行相应的操作界面元素的代码。

主要有两种方法可以在工作线程中完成UI界面元素的操作:

1.Control.Invoke

2.SynchronizationContext

下面的例子同时使用了这两个方法做演示(SynchronizationContext也可以使用Send来调用UI线程中的方法委托)

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

using System.Threading;

namespace WF_SynchronizationContext_Test

{

    public partial class Form1 : Form

    {

        private SynchronizationContext sc = null;

        public delegate void ShowText(object o);

        public Form1()

        {

            InitializeComponent();

            Thread.CurrentThread.Name = "mainthread";

            sc = SynchronizationContext.Current;

        }

        public void ShowStatus(object o)

        {           

            this.label1.Text = string.Format("in sub thread:{0}", Thread.CurrentThread.Name);

        }

        private void button1_Click(object sender, EventArgs e)

        {

            ShowText showTxt = new ShowText(ShowStatus);

            Thread thread = new Thread(o=>

            {

                Thread.CurrentThread.Name = "subthread";

                Form1 f = o as Form1;

                if (f != null)

                {

                    f.Invoke(showTxt);

                    string s = Thread.CurrentThread.Name;

                }

            });

            thread.IsBackground = true;

            thread.Start(this);

        }

        private void button2_Click(object sender, EventArgs e)

        {

            Thread thread = new Thread(o =>

                {

                    Thread.CurrentThread.Name = "subthread";

                    SynchronizationContext sc = o as SynchronizationContext;

                    if (sc != null)

                    {

                        sc.Post(ShowStatus,  null);

                    }

                    string s = Thread.CurrentThread.Name;

                });

            thread.IsBackground = true;

            thread.Start(this.sc);

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: