当前位置:   article > 正文

工作线程操作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);
        }
    }
}

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号