• 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)<对象执行方法>

  • 相关阅读:
    zabbix监控windows案例
    Ansible自动化运维工具-上
    Nagios监控的部署与配置
    ELK+Redis+Nginx服务数据存储以及Nginx日志的收集
    ELK5.3日志分析平台&部署
    Centos7X部署Zabbix监控
    LVS+Keepalived负载均衡
    Nginx+tomcat负载均衡
    smokeping
    Err.number错误号和可捕获的 Microsoft access 数据库引擎和 DAO错误说明
  • 原文地址:https://www.cnblogs.com/eric-gms/p/3475175.html
Copyright © 2020-2023  润新知