zoukankan      html  css  js  c++  java
  • C#编程应用线程与委托


    1. C#开发C/S程序,有时需要几个端,如服务器端,管理端,客户端等等, 端与端之间是不同线程或者进程,这就涉及跨线程调用的问题,

        使用委托或者异步线程是必不可少的,这里是一个简单的委托线程,即通过委托调用另外一个线程;

    2. 有图有真相:

       

    3. 源码:

    View Code
    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 ThreadControlExample
    {
        public partial class Form1 : Form
        {
            Thread thread1;
            Thread thread2;
            delegate void AppendStringDelegate(string str);
            AppendStringDelegate appendStringDelegate;
            public Form1()
            {
                InitializeComponent();
                appendStringDelegate = new AppendStringDelegate(AppendString);
            }

            private void AppendString(string str)
            {
               richTextBox1.Text += str;
            }

            private void Method1()
            {
                while (true)
                {
                    Thread.Sleep(100);   //线程1休眠100毫秒
                    richTextBox1.Invoke(appendStringDelegate, "a");
                }
            }
            private void Method2()
            {
                while (true)
                {
                    Thread.Sleep(100);   //线程2休眠100毫秒
                    richTextBox1.Invoke(appendStringDelegate, "b");
                }
            }

            private void buttonStart_Click(object sender, EventArgs e)
            {
                richTextBox1.Text = "";
                thread1 = new Thread(new ThreadStart(Method1));
                thread2 = new Thread(new ThreadStart(Method2));
                thread1.Start();
                thread2.Start();
            }

            private void buttonStop_Click(object sender, EventArgs e)
            {
                thread1.Abort();
                thread1.Join();
                thread2.Abort();
                thread2.Join();
                MessageBox.Show("线程1、2终止成功");
            }

        }
    }
  • 相关阅读:
    第二部分 高数_9 优化
    第二部分 高数_8 泰勒公式、麦克劳林公式和线性化
    第二部分 高数_7 二元符合函数的求导法则
    第二部分 高数_6 高阶偏导数
    第二部分 高数_5 多元函数的导数
    第二部分 高数_4 函数的积分
    第二部分 高数_3 函数的微分
    第二部分 高数_2 导数
    第二部分 高数_1 极限
    第一部分 现代_4 特征值和特征向量
  • 原文地址:https://www.cnblogs.com/dzone/p/2194934.html
Copyright © 2011-2022 走看看