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

posted on 2013-12-15 12:55  月&&生  阅读(201)  评论(0编辑  收藏  举报