zoukankan      html  css  js  c++  java
  • C# 跨线程操作UI元素

    参考:http://www.cnblogs.com/zhangpengshou/archive/2008/04/28/1175289.html
    http://blog.csdn.net/ghevinn/article/details/12065511

    1. 使用MethodInvoker

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    namespace InvokeTest
    {
    public partial class Form1 : Form
    {
        public static int x = 0;
        public Form1()
        {
            InitializeComponent();
            Thread thread = new Thread(new ThreadStart(ThreadProc));
            thread.IsBackground = true;
            thread.Start();
        }
        public void changeLable()
        {
            x++;
            label1.Text = Convert.ToString(x);
        }
        public void ThreadProc()
        {
            MethodInvoker send = new MethodInvoker(changeLable);            
            while (true)
            {
                Thread.Sleep(1000);
                BeginInvoke(send);
            }
        }
    }
    }
    

    2. 使用EventHandler

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace InvokeTest
    {
    public partial class Form1 : Form
    {
        public static int x = 0;
    
        public Form1()
        {
            InitializeComponent();
            Thread thread = new Thread(new ThreadStart(ThreadProc));
            thread.IsBackground = true;
            thread.Start();
        }
    
        public void ThreadProc()
        {
            EventHandler send = new EventHandler(label1_Click);
            
            while (true)
            {
                Thread.Sleep(1000);
                BeginInvoke(send);
            }
        }
    
        private void label1_Click(object sender, EventArgs e)
        {
            x++;
            label1.Text = Convert.ToString(x);
        }
    }
    }
  • 相关阅读:
    Linux--sed命令
    Linux--cut命令
    Android--aapt命令
    Shell--基础知识
    Linux--vim编辑器和文件恢复
    Linux--基本命令
    Linux--添加用户
    Linux--网络配置
    SpringCloud--Ribbon负载均衡
    第一阶段冲刺4
  • 原文地址:https://www.cnblogs.com/yinsua/p/4758001.html
Copyright © 2011-2022 走看看