C#线程学习

原创 2006年05月22日 14:11:00

任务:在一个主线程中同时开启三个线程,每个线程中执行相同的数据插入动作,只是数据不同。
     数据库在得到插入的响应后,作相应的处理,如果为数值1,延时10秒,为2延时5,为3不延时.
目的:体验C#多线程处理

后台数据库的淮备:
1.建表
create table dd (id Tinyint )
2.建触发器
create trigger tg_dd_ins on dd for insert
as
begin
  declare @v Tinyint
  select @v=id from inserted
  if @v=1
     waitfor delay '00:00:10'
  else if @v=2
     waitfor delay '00:00:05'
end
 

3.C#中处理过程
Form1.CS

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
using System.Threading;

namespace threadprg
{

    enum outputkind { otui, otfile };

    public partial class Form1 : Form
    {

        private const string G_cnnstring = "Persist Security Info=False;User ID=user;Password=m258;Initial Catalog=test;Server=MSSQL";


        private outputkind foutput;

        outputkind Foutput
        {
            set { foutput = value; }
            get { return foutput; }
          
        }

        public Form1()
        {
            InitializeComponent();
        }

        delegate void uidelegate();

        private uidelegate d;

        private void threadonedelegateexec()
        {
            if (this.InvokeRequired)
            {
                d = new uidelegate(threadonedelegateexec);
                this.Invoke(d, null);
            }
            else
                this.textBox1.Text = "thread one exec finished!";

        }

        private void threadtwodelegateexec()
        {
            if (this.InvokeRequired)
            {
                d = new uidelegate(threadtwodelegateexec);
                this.Invoke(d,null);
            }
            else
                this.textBox2.Text = "thread two exec finished!";
        }

        private void threadthreedelegateexec()
        {
            if (this.InvokeRequired)
            {
                d = new uidelegate(threadthreedelegateexec);
                this.Invoke(d, null);
            }
            else
            this.textBox3.Text = "thread three exec finished!";
       }


        private void thread1exec()
        {
            SqlConnection cnn = new SqlConnection(G_cnnstring);
            cnn.Open();
            SqlCommand cmd = new SqlCommand("insert into dd(id) values (1)");
            cmd.Connection = cnn;
            cmd.ExecuteNonQuery();
           
            switch (foutput)
            {
                case outputkind.otui:
                    threadonedelegateexec();
                    break;
                case outputkind.otfile:
                    WriteToAlertFile("threadonelog", "thread one exec finished!");
                    break;
                default:
                    break;
            }

            cnn.Close();           

        }

        private void thread2exec()
        {
            SqlConnection cnn = new SqlConnection(G_cnnstring);
            cnn.Open();
            SqlCommand cmd = new SqlCommand("insert into dd(id) values(2)");
            cmd.Connection = cnn;
            cmd.ExecuteNonQuery();

            switch (foutput)
            {
                case outputkind.otui:
                    threadtwodelegateexec();
                    break;
                case outputkind.otfile:
                    WriteToAlertFile("threadtwolog", "thread two exec finished!");
                    break;
                default: break;
             }
            cnn.Close();
        }

        private void thread3exec()
        {
            SqlConnection cnn = new SqlConnection(G_cnnstring);
            SqlCommand cmd = new SqlCommand("insert into dd(id) values(3)");
            cnn.Open();
            cmd.Connection = cnn;

            cmd.ExecuteNonQuery();
            switch (foutput)
            {
                case outputkind.otui:
                        threadthreedelegateexec();
                        break;
                case outputkind.otfile:
                    WriteToAlertFile("threadthreeLog","Thread three exec finished!");
                        break;
                default:
                    break;
            }

            cnn.Close();
        }

        private bool WriteToAlertFile(String xLogFileName, String xMessage)
        {
            return this.WriteToAlertFile(xLogFileName, xMessage, "D");
        }

        private bool WriteToAlertFile(String xLogFileName,String xMessage,String xFileType)
        {
            bool ret;
            String mFileName,mRunPosition;
            mRunPosition=Application.ExecutablePath+@"/log";
            mRunPosition = @"c:/log";
            try
            {
                if (!Directory.Exists(mRunPosition))
                {
                    Directory.CreateDirectory(mRunPosition);
                }
                switch (xFileType)
                {
                    case "D":
                        mFileName = mRunPosition + @"/Alert_" + xLogFileName + "_" + System.DateTime.Now.ToString("yyyyMMdd");
                        break;
                    case "M":
                        mFileName = mRunPosition + @"/Alert_" + xLogFileName + "_" + System.DateTime.Now.ToString("yyyyMM");
                        break;
                    case "Y":
                        mFileName = mRunPosition + @"/Alert_" + xLogFileName + "_" + System.DateTime.Now.ToString("yyyy");
                        break;
                    default:
                        mFileName = mRunPosition + @"/Alert_" + xLogFileName + "-" + System.DateTime.Now.ToString("YYYYMMDD");
                        break;
                }

                if (xLogFileName.IndexOf(".") == -1)

                    mFileName =mFileName+ ".log";

               using(StreamWriter sw=new StreamWriter(mFileName))
               {
                  sw.WriteLine(System.DateTime.Now.ToString(@"{yyyy/MM/dd HH:mm:ss}")+xMessage);
               }


            
             }
            catch { ret=false; };
     
            ret=true;
           

           
            return ret;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            foutput = outputkind.otui;
            //foutput = outputkind.otfile;
             Thread T1 = new Thread(new ThreadStart(thread1exec));
             T1.Start();
           
            Thread T2 = new Thread(new ThreadStart(thread2exec));
            T2.Start();

            Thread T3 = new Thread(new ThreadStart(thread3exec));
            T3.Start();

         
         
        
            
        }
     
     }


}

 

Form1.Designer.cs

namespace threadprg
{
    partial class Form1
    {
        /// <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);
        }

        #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.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.textBox3 = new System.Windows.Forms.TextBox();
            this.dataSet1 = new System.Data.DataSet();
            ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).BeginInit();
            this.SuspendLayout();
            //
            // button1
            //
            this.button1.Location = new System.Drawing.Point(180, 142);
            this.button1.Name = "button1";
            this.button1.Size = new System.Drawing.Size(134, 43);
            this.button1.TabIndex = 0;
            this.button1.Text = "Go!!!";
            this.button1.UseVisualStyleBackColor = true;
            //
            // textBox1
            //
            this.textBox1.Location = new System.Drawing.Point(163, 31);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(160, 20);
            this.textBox1.TabIndex = 1;
            //
            // textBox2
            //
            this.textBox2.Location = new System.Drawing.Point(163, 67);
            this.textBox2.Name = "textBox2";
            this.textBox2.Size = new System.Drawing.Size(160, 20);
            this.textBox2.TabIndex = 2;
            //
            // textBox3
            //
            this.textBox3.Location = new System.Drawing.Point(163, 103);
            this.textBox3.Name = "textBox3";
            this.textBox3.Size = new System.Drawing.Size(160, 20);
            this.textBox3.TabIndex = 1;
            //
            // dataSet1
            //
            this.dataSet1.DataSetName = "NewDataSet";
            //
            // Form1
            //
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(534, 266);
            this.Controls.Add(this.textBox3);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.Load += new System.EventHandler(this.Form1_Load);
            ((System.ComponentModel.ISupportInitialize)(this.dataSet1)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.Button button1;
        private System.Windows.Forms.TextBox textBox1;
        private System.Windows.Forms.TextBox textBox2;
        private System.Windows.Forms.TextBox textBox3;
        private System.Data.DataSet dataSet1;
    }
}

 

 

 点击这里给我发消息

python线程进程、异步IO

多线程是指从软件或者硬件上实现多个线程并发执行的技术。具有多线程能力的计算机因有硬件支持而能够在同一时间 执行多于一个线程,进而提升整体处理性能。 该章节主要包括线程进程的概念,基于python的线程进程实现,GIL锁的影响,消费者生产者模型,进程池的应用以及IO模型的介绍,一句话概括本章的内容就是:实现并发编程,即计算机能够同时处理多个任务。
  • 2017年03月06日 18:23

C# 多线程教程(C#学习日记 2017-10-16)

转载地址:点击打开链接 (1)不需要传递参数,也不需要返回参数 ThreadStart是一个委托,这个委托的定义为void ThreadStart(),没有参数与返回值。 class P...
  • yeyoushen000000
  • yeyoushen000000
  • 2017-10-16 10:05:16
  • 244

进程和线程学习理解

1 fork基本概念 一个进程,包括代码、数据和分配给进程的资源。fork()函数通过系统调用创建一个与原来进程几乎完全相同的进程,也就是两个进程可以做完全相同的事,但如果初始参数或者传入的变量不同...
  • shenwanjiang111
  • shenwanjiang111
  • 2016-04-28 10:31:59
  • 1861

C#多线程学习(三) 生产者和消费者 1——解决线程间冲突的关键

前面说过,每个线程都有自己的资源,但是代码区是共享的,即每个线程都可以执行相同的函数。这可能带来的问题就是几个线程同时执行一个函数,导致数据的混乱,产生不可预料的结果,因此我们必须避免这种情况的发生。...
  • kenkao
  • kenkao
  • 2010-03-26 08:18:00
  • 2283

关于C# 多线程学习

  • 2010年01月19日 17:59
  • 4KB
  • 下载

C#学习之多线程开发技术(一)

----------------------先聊聊进程吧--------------------------------- 进程的概念主要有两点:       第一,进程是一个实体。每一个进程都有...
  • HK_5788
  • HK_5788
  • 2015-10-06 20:25:47
  • 356

C#.net多线程的学习 (自学篇)

    .net框架的System.Threading命名空间提供了一些可以进行多线程编程的类和接口。除同步线程活动和访问数据的类(Mutex、Monitor、Interlocked、AutoRese...
  • DVD_01
  • DVD_01
  • 2006-05-12 08:22:00
  • 2379

C# 在多线程中如何调用Winform

问题的产生:   我的WinForm程序中有一个用于更新主窗口的工作线程(worker thread),但文档中却提示我不能在多线程中调用这个form(为什么?),而事实上我在调用时程序常常会崩掉。...
  • taoerit
  • taoerit
  • 2017-02-14 09:25:52
  • 803

C#线程参考手册 线程学习

  • 2010年11月17日 13:06
  • 5.01MB
  • 下载

C# 多线程问题处理小结

这两天用到一个需要使用多线程的问题,纠结了一天终于解决了! 问题描述:程序启动后,需要解析文件,由于文件太大,所以解析中会使程序卡顿,故需要额外弹出一个Loading窗体显示“Loading...”...
  • gu263278505
  • gu263278505
  • 2014-11-25 17:01:25
  • 734
收藏助手
不良信息举报
您举报文章:C#线程学习
举报原因:
原因补充:

(最多只允许输入30个字)