zoukankan      html  css  js  c++  java
  • C#编程应用简单线程


    1. 主题:C#开发当中,多线程很多时候都必不可少的,尤其有处理多任务的情况下;

    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 ThreadExample
    {
        public partial class Form1 : Form
        {
            StringBuilder sb = new StringBuilder();
            Thread thread1;
            Thread thread2;

            public Form1()
            {
                InitializeComponent();
            }
            private void AppendString(string s)
            {
                lock (sb)
                {
                    sb.Append(s);
                }
            }
            public void Method1()
            {
                while (true)
                {
                    Thread.Sleep(100);   //线程休眠100毫秒
                    AppendString("a");
                }
            }
            public void Method2()
            {
                while (true)
                {
                    Thread.Sleep(100);   //线程休眠100毫秒
                    AppendString("b");
                }
            }

            private void buttonStart_Click(object sender, EventArgs e)
            {
                sb.Remove(0, sb.Length);
                timer1.Enabled = true;
                thread1 = new Thread(new ThreadStart(Method1));
                thread2 = new Thread(new ThreadStart(Method2));
                thread1.Start();
                thread2.Start();
            }

            private void buttonAbort_Click(object sender, EventArgs e)
            {
                thread1.Abort();
                thread1.Join(10);
                thread2.Abort();
                thread2.Join(10);
            }

            private void timer1_Tick(object sender, EventArgs e)
            {
                if (thread1.IsAlive == true || thread2.IsAlive == true)
                {
                    richTextBox1.Text = sb.ToString();
                }
                else
                {
                    timer1.Enabled = false;
                }
            }
        }
    }
  • 相关阅读:
    HelperC#常用的防sql注入的关键词检测
    工业自动化产线名词
    C#使用单例模式
    cmt焊接和mig焊区别
    数据库表命名规范
    UIImagePickerController类 照相 或者 从相册取相片 (iphone and ipad)
    UIActionSheet类 在 iphone和ipad 中的不同
    navigationBarrespondsToSelector方法 判断对象是否接受到了某个方法
    设置自定义UIButton的背景图片
    AVFoundation.framwork 及其 部分类的使用
  • 原文地址:https://www.cnblogs.com/dzone/p/2194923.html
Copyright © 2011-2022 走看看