首页 > 编程语言 >C#如何进行多线程编程

C#如何进行多线程编程

时间:2023-06-13 16:04:09浏览次数:39  
标签:lblResult C# 编程 System Windows btnStart btnStop new 多线程


C#如何进行多线程编程


由于多线程编程非常复杂,这个小例子只能算是一个入门线的知识点吧

首先建一个应用程序项目,命名为ThreadExample,在窗体上放一个文本框(textBox1) ,一个标签(lblResult),再放两个按钮,分别命名为btnStart、btnStop。

窗体代码:



namespace 
   ThreadExample
{
    partial  
  class 
   ThreadExample
    {
         
  /**/ 
  /// 
    
  <summary> 
  
         
  /// 
   Required designer variable.
         
  /// 
    
  </summary> 
  
 
           
  private 
   System.ComponentModel.IContainer components  
  = 
    
  null 
  ;

         
  /**/ 
  /// 
    
  <summary> 
  
         
  /// 
   Clean up any resources being used.
         
  /// 
    
  </summary> 
  
         
  /// 
    
  <param name="disposing"> 
  true if managed resources should be disposed; otherwise, false. 
  </param> 
  
 
           
  protected 
    
  override 
    
  void 
   Dispose( 
  bool 
   disposing)
        {
             
  if 
   (disposing  
  && 
   (components  
  != 
    
  null 
  ))
            {
                components.Dispose();
            }
             
  base 
  .Dispose(disposing);
        }

        Windows Form Designer generated code 
  #region 
   Windows Form Designer generated code 
  

         
  /**/ 
  /// 
    
  <summary> 
  
         
  /// 
   Required method for Designer support - do not modify
         
  /// 
   the contents of this method with the code editor.
         
  /// 
    
  </summary> 
  
 
           
  private 
    
  void 
   InitializeComponent()
        {
             
  this 
  .btnStart  
  = 
    
  new 
   System.Windows.Forms.Button();
             
  this 
  .btnStop  
  = 
    
  new 
   System.Windows.Forms.Button();
             
  this 
  .button1  
  = 
    
  new 
   System.Windows.Forms.Button();
             
  this 
  .textBox1  
  = 
    
  new 
   System.Windows.Forms.TextBox();
             
  this 
  .lblResult  
  = 
    
  new 
   System.Windows.Forms.Label();
             
  this 
  .SuspendLayout();
             
  // 
   
             
  // 
   btnStart
             
  // 
    
  
 
               
  this 
  .btnStart.Location  
  = 
    
  new 
   System.Drawing.Point( 
  14 
  ,  
  38 
  );
             
  this 
  .btnStart.Name  
  = 
    
  " 
  btnStart 
  " 
  ;
             
  this 
  .btnStart.Size  
  = 
    
  new 
   System.Drawing.Size( 
  75 
  ,  
  23 
  );
             
  this 
  .btnStart.TabIndex  
  = 
    
  0 
  ;
             
  this 
  .btnStart.Text  
  = 
    
  " 
  启动 
  " 
  ;
             
  this 
  .btnStart.Click  
  += 
    
  new 
   System.EventHandler( 
  this 
  .btnStart_Click);
             
  // 
   
             
  // 
   btnStop
             
  // 
    
  
 
               
  this 
  .btnStop.Location  
  = 
    
  new 
   System.Drawing.Point( 
  14 
  ,  
  68 
  );
             
  this 
  .btnStop.Name  
  = 
    
  " 
  btnStop 
  " 
  ;
             
  this 
  .btnStop.Size  
  = 
    
  new 
   System.Drawing.Size( 
  75 
  ,  
  23 
  );
             
  this 
  .btnStop.TabIndex  
  = 
    
  1 
  ;
             
  this 
  .btnStop.Text  
  = 
    
  " 
  停止 
  " 
  ;
             
  this 
  .btnStop.Click  
  += 
    
  new 
   System.EventHandler( 
  this 
  .btnStop_Click);
             
  // 
   
             
  // 
   button1
             
  // 
    
  
 
               
  this 
  .button1.Location  
  = 
    
  new 
   System.Drawing.Point( 
  14 
  ,  
  97 
  );
             
  this 
  .button1.Name  
  = 
    
  " 
  button1 
  " 
  ;
             
  this 
  .button1.Size  
  = 
    
  new 
   System.Drawing.Size( 
  75 
  ,  
  23 
  );
             
  this 
  .button1.TabIndex  
  = 
    
  3 
  ;
             
  this 
  .button1.Text  
  = 
    
  " 
  关闭 
  " 
  ;
             
  this 
  .button1.Click  
  += 
    
  new 
   System.EventHandler( 
  this 
  .button1_Click);
             
  // 
   
             
  // 
   textBox1
             
  // 
    
  
 
               
  this 
  .textBox1.Location  
  = 
    
  new 
   System.Drawing.Point( 
  14 
  ,  
  11 
  );
             
  this 
  .textBox1.Name  
  = 
    
  " 
  textBox1 
  " 
  ;
             
  this 
  .textBox1.Size  
  = 
    
  new 
   System.Drawing.Size( 
  75 
  ,  
  21 
  );
             
  this 
  .textBox1.TabIndex  
  = 
    
  4 
  ;
             
  this 
  .textBox1.Text  
  = 
    
  " 
  200 
  " 
  ;
             
  // 
   
             
  // 
   lblResult
             
  // 
    
  
 
               
  this 
  .lblResult.AutoSize  
  = 
    
  true 
  ;
             
  this 
  .lblResult.Location  
  = 
    
  new 
   System.Drawing.Point( 
  12 
  ,  
  139 
  );
             
  this 
  .lblResult.Name  
  = 
    
  " 
  lblResult 
  " 
  ;
             
  this 
  .lblResult.Size  
  = 
    
  new 
   System.Drawing.Size( 
  23 
  ,  
  12 
  );
             
  this 
  .lblResult.TabIndex  
  = 
    
  5 
  ;
             
  this 
  .lblResult.Text  
  = 
    
  " 
  0/0 
  " 
  ;
             
  // 
   
             
  // 
   ThreadExample
             
  // 
    
  
 
               
  this 
  .AutoScaleDimensions  
  = 
    
  new 
   System.Drawing.SizeF(6F, 12F);
             
  this 
  .AutoScaleMode  
  = 
   System.Windows.Forms.AutoScaleMode.Font;
             
  this 
  .ClientSize  
  = 
    
  new 
   System.Drawing.Size( 
  104 
  ,  
  164 
  );
             
  this 
  .Controls.Add( 
  this 
  .lblResult);
             
  this 
  .Controls.Add( 
  this 
  .textBox1);
             
  this 
  .Controls.Add( 
  this 
  .button1);
             
  this 
  .Controls.Add( 
  this 
  .btnStop);
             
  this 
  .Controls.Add( 
  this 
  .btnStart);
             
  this 
  .Name  
  = 
    
  " 
  ThreadExample 
  " 
  ;
             
  this 
  .Text  
  = 
    
  " 
  Form1 
  " 
  ;
             
  this 
  .ResumeLayout( 
  false 
  );
             
  this 
  .PerformLayout();

        }

         
  #endregion 
  

         
  private 
   System.Windows.Forms.Button btnStart;
         
  private 
   System.Windows.Forms.Button btnStop;
         
  private 
   System.Windows.Forms.Button button1;
         
  private 
   System.Windows.Forms.TextBox textBox1;
         
  private 
   System.Windows.Forms.Label lblResult;
    }
}



程序代码:


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 
   ThreadExample
{
     
  public 
   partial  
  class 
   ThreadExample : Form
    {
         
  // 
  声明一个线程 
  
 
           
  private 
   Thread timerThread;
         
  // 
  声明一个变量,用来存储label值 
  
 
           
  int 
   count, i  
  = 
    
  0 
  ;

         
  public 
   ThreadExample()
        {
            InitializeComponent();
        }

         
  // 
  把label的值加1; 
  
 
           
  public 
    
  void 
   AddData()
        {
             
  // 
  显示lable的值 
  
 
               
  if 
   (i  
  == 
   count)
                i  
  = 
    
  0 
  ;
             
  this 
  .lblResult.Text  
  = 
   i.ToString()  
  + 
    
  " 
  / 
  " 
    
  + 
   count.ToString();
            i 
  ++ 
  ;
        }

         
  // 
  更新线程 
  
 
           
  public 
    
  void 
   UpdataThread()
        {
             
  try 
  
            {
                 
  // 
  在对控件的调用方法进行调用时,或需要一个简单委托又不想自己定义时可以使用该委托。 
  
 
                  MethodInvoker mi  
  = 
    
  new 
   MethodInvoker( 
  this 
  .AddData);
                 
  while 
   ( 
  true 
  )
                {
                     
  // 
  在创建控件的基础句柄所在线程上异步执行指定的委托 
  
 
                       
  this 
  .BeginInvoke(mi);
                    Thread.Sleep( 
  50 
  );
                }
            }
             
  catch 
   (ThreadInterruptedException)
            {
                 
  // 
  针对具体问题定制异常抛出显示 
  
 
              }
             
  finally 
  
            {
                 
  // 
  做一些处理 
  
 
              }
        }

         
  // 
  启动线程 
  
 
           
  public 
    
  void 
   StartThread()
        {
            StopThread();
            timerThread  
  = 
    
  new 
   Thread( 
  new 
   ThreadStart(UpdataThread));
             
  // 
  获取或设置一个值,该值指示某个线程是否为后台线程。 
  
 
              timerThread.IsBackground  
  = 
    
  true 
  ;
            timerThread.Start();
        }

         
  // 
  停止线程 
  
 
           
  public 
    
  void 
   StopThread()
        {
             
  if 
   (timerThread  
  != 
    
  null 
  )
            {
                 
  // 
  中断线程 
  
 
                  timerThread.Interrupt();
                timerThread  
  = 
    
  null 
  ;
            }
        }

         
  // 
  启动线程,显示结果 
  
 
           
  private 
    
  void 
   btnStart_Click( 
  object 
   sender, EventArgs e)
        {
             
  // 
  调用线程启动函数 
  
 
              count  
  = 
    
  int 
  .Parse(textBox1.Text);
             
  this 
  .StartThread();
        }

         
  // 
  停止线程 
  
 
           
  private 
    
  void 
   btnStop_Click( 
  object 
   sender, EventArgs e)
        {
             
  // 
  调用线程停止函数 
  
 
               
  this 
  .StopThread();
        }       
    }
}



编译后,运行,在文本框中输入200,点击开始按钮,标签为动态增长,点击停止可以暫停程序的执行。

标签:lblResult,C#,编程,System,Windows,btnStart,btnStop,new,多线程
From: https://blog.51cto.com/guosisoft/6470975

相关文章

  • C++ Builder 初学问与答(二)
     2.文本输入组件11)问:如果要实现文本输入,在C++Builder中应该怎么办? 答:C++Builder常用文本输入组件来实现,常用的文本输入组件有Edit、MaskEdit、Memo和RichEdit。他们的主要不同在于Edit和MaskEdit用于输入单行文本,而Memo和RichEdit可以输入多行文本。此外Label组件也可用来进行......
  • C#连接MySql数据库的方法
     用MySQLDriverCS连接MySQL数据库   先下载和安装MySQLDriverCS,地址:   http://sourceforge.net/projects/mysqldrivercs/   在安装文件夹下面找到MySQLDriver.dll,然后将MySQLDriver.dll添加引用到项目中   注:我下载的是版本是MySQLDriverCS-n-EasyQueryTools-4.0......
  • C++ Builder 初学问与答(一)
    一直以来都想写一点为BCB初学者快速入门的东西,前不久写了几篇《闲谈BCB》想把自己学习BCB中如何来解决难点的方法说给大家,没想到被骂得不成样子。本想不写了,但觉得这些东西留下来能做什么呢?还是用另一种方法来重新演译我的思维吧,最近有些忙,那几篇没有写完的文章,我也会尽快写完的,至......
  • WinForm下DataGridView导出Excel的实现
    WinForm下DataGridView导出Excel的实现 1.说明:导出的效率说不上很高,但至少是可以接收的.参考网上很多高效导出Excel的方法,实现到时能够实现的,导出速度也很快,不过缺陷在与不能很好的进行单元格的格式化,比如上图中的"拼音码"字段中的值"000000000012120",在导出后就显示"1212......
  • 使用C#的WebService实现客户端软件的更新
    由于项目原因,要实施的客户离作者太远,考虑提供软件的在线升级功能.我们如何实现呢!先讲下思路.思路:先实现WEB端的开发,主要考虑使用WEBService技术,提供远程服务的调用函数,返回一个文件的字节内容,然后写一个升级程序客户端,分发给客户使用的机器中,(可以随客户的软件一起安装).......
  • 基于.NET的Web Service技术的分布式异构数据库的集成
    摘要:本文分析了WebService的特点,提出了一种基于Microsoft.NET的WebService技术访问分布异构数据库的体系结构,并采用.NET技术实现了原型系统。在原型系统中,使用WebService将分布于Internet上的不同的数据库系统中的数据集成,向访问数据库的应用程序提供统一的数据操作接口,实现......
  • Apache Http Server 路径穿越漏洞复现(CVE-2021-41773)
    ApacheHttpServer路径穿越漏洞复现ApacheHttpServer路径穿越漏洞概述ApacheHttpServer简介ApacheHTTPServer(简称Apache)是Apache软件基金会的一个开放源码的网页服务器软件,可以在大多数电脑操作系统中运行。由于其跨平台和安全性,被广泛使用,是最流行的Web服务器......
  • 【pyqt】报错TypeError: decorated slot has no signature compatible with RecorderP
    一、场景  运行pyqt报错TypeError:decoratedslothasnosignaturecompatiblewithRecorderPlayerProxy.sig_mode_update[object] 二、代码@Slot(int)defupdate_mode(self,mode):...... 三、解决方法  将int去除即可  参考链接:p......
  • NVIDIA Maxine Video Effects SDK 編程指南 - 实践小记
    NVIDIAMaxineVideoEffectsSDK編程指南 -实践小记本篇博客重点只说VideoEffect的部分,此外还有AudioEffect的部分、还有AR部分,不在本篇范围内。本文由重庆Debug原创NVIDIAMaxineVideoEffects支持基于AI的视觉效果,这些效果可以输入标准网络摄像头画面数据,同时也可以......
  • c#排序算法
    1.没有一种排序算法是万能的最快算法,因为最快的排序算法取决于数据的性质和排序要求。然而,对于一般情况下的排序问题,以下算法通常被认为是最快的:快速排序(QuickSort):这是一种基于分治思想的常见排序算法。其平均时间复杂度为O(nlogn)。因为其平均情况下时间复杂度相对较快,加上......