zoukankan      html  css  js  c++  java
  • C# 多线程

    1、摇奖机的实现

    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 _09_摇奖机
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                Control.CheckForIllegalCrossThreadCalls = false;
            }
            Thread th;
            bool isStart = false;
            private void btnStart_Click(object sender, EventArgs e)
            {
                //如果线程正在执行,则终止线程。
                if (isStart)
                {
                    th.Abort();
                    btnStart.Text = "开始";
                    isStart = false;
                }
                else
                { 
                    th = new Thread(Test);
                    th.IsBackground = true;
                    th.Start();
                    btnStart.Text = "停止";
                    isStart = true;
                }
            }
    
            void Test()
            {
                Random random = new Random();
                while (true)
                {
                    //遍历窗体上的label设置随机数
                    for (int i = 0; i < this.Controls.Count; i++)
                    {
                        Control c = this.Controls[i];
    
                        if (c is Label)
                        {
                            if (c.Name != "lblResult")
                            {
                                c.Text = random.Next(0, 10).ToString();
                            }
                        }
    
                    }
                    Thread.Sleep(80);
                }
            }
    
            private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                //关闭窗体之前,先终止线程,否则会报错
                if (th != null && th.IsAlive)
                {
                    th.Abort();
                }
            }
        }
    }
    View Code

     2、并行计算与多线程

    var result=list.AsParallel().WithDegreeOfParallelism(6).Select(e => DoItAgent(e)).ToList();

    AsParallel()<System.Threading.Tasks.::.Parallel类>

    WithDegreeOfParallelism<线程数量>

     DoItAgent(e)<对象执行方法>

  • 相关阅读:
    arduino入门学习实现语音控制LED灯
    c# 实现串口编程-操作LED屏幕
    腾讯地图 获取各种情况的总距离
    js播放wav文件,兼容主流浏览器,兼容多浏览器
    工厂方法模式
    依赖倒转模式
    设计模式——开放封闭原则
    设计模式——单一职责原则
    策略模式
    简单工厂模式
  • 原文地址:https://www.cnblogs.com/eric-gms/p/3475175.html
Copyright © 2011-2022 走看看