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

  • 相关阅读:
    tab选项卡可自动播放
    鼠标跟随效果
    初识html5
    浅谈权限设计
    css表格撑大问题解决
    通用数据权限管理系统设计
    样式兼容IE7
    RBAC用户角色权限设计
    大话权限设计
    一个简易实用的web权限管理模块的应用与实现
  • 原文地址:https://www.cnblogs.com/eric-gms/p/3475175.html
Copyright © 2011-2022 走看看