zoukankan      html  css  js  c++  java
  • [C# 学习]委托和线程

    委托有点像C语言的函数指针,简单总结一下如何使用委托。

    1. 声明一个委托

    public delegate void LabelSetEventHandler(Label la, string str);

    2. 定义委托

    LabelSetEventHandler LabelSet;

    3. 实例化委托

    LabelSet = new LabelSetEventHandler(ChangeLabel);

    下面以实际例子来说明应用,现有一个窗口,一个按钮和一个Label, 希望通过单击按钮事件来改变Label显示的内容,通过委托的方法实现。

    完整代码如下:

    namespace Thread_
    {
        public partial class design : Form
        {
            public delegate void LabelSetEventHandler(string str);
            LabelSetEventHandler LabelSet;
            
            public design()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                LabelSet = ChangeLabel1; 
                LabelSet("Hi");
            }
    
            private  void ChangeLabel1(string str)
            {
                label1.Text = str;
            }
      }
    }

    有了以上委托的知识,那么我们就可以通过委托来跨线程安全调用控件了。

    现在在上面的基础上增加一个按键Button2,要求Button1的单击事件开启一个线程,改变Label1的内容为“Thread1”,Button2的单击事件开启另一个线程,改变Label1的内容为"Thread2"。一下是程序的完整代码。

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Threading;
    
    namespace Thread_
    {
        public partial class design : Form
        {
            public delegate void LabelSetEventHandler(string str);
            LabelSetEventHandler LabelSet;
            
            public design()
            {
                InitializeComponent();
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                Thread th = new Thread(Thread1);
                th.Start();
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                Thread th = new Thread(Thread2);
                th.Start();
    
            }
            private  void ChangeLabel1(string str)
            {
                label1.Text = str;
            }
    
            private void Thread1()
            {
                LabelSet = ChangeLabel1;
                BeginInvoke(LabelSet, "Thread1");
            }
    
            private void Thread2()
            {
                LabelSet = ChangeLabel1;
                BeginInvoke(LabelSet, "Thread2");
            }
      }
    }
  • 相关阅读:
    LeetCode:数组(三)
    LeetCode:数组(二)
    LeetCode:数组(一)
    python实现栈的基本操作
    python基本内置函数
    Pycharm的常见Debug调试方法(持续更新)
    计算广告系列(一)-基本概念整理
    es与solr对比
    数据库优化
    java线程池
  • 原文地址:https://www.cnblogs.com/mr-bike/p/3721646.html
Copyright © 2011-2022 走看看