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

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);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值