创建线程
来源:互联网 发布:微信客户端 mac 编辑:程序博客网 时间:2024/05/18 21:43
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 ThreadWinApp{ public partial class Form1 : Form { private Thread trd; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("This is the main thread"); } private void ThreadTask() { int stp; int newval; Random rnd = new Random(); while (true) { stp = this.progressBar1.Step * rnd.Next(-1,2); newval = this.progressBar1.Value + stp; if (newval > this.progressBar1.Maximum) newval = this.progressBar1.Maximum; else if (newval < this.progressBar1.Minimum) newval = this.progressBar1.Minimum; this.progressBar1.Value = newval; Thread.Sleep(100); } } private void Form1_Load(object sender, EventArgs e) { trd = new Thread(new ThreadStart(this.ThreadTask)); trd.IsBackground = true; trd.Start(); Control.CheckForIllegalCrossThreadCalls = false;//排除错误 线程间操作无效: 从不是创建控件“progressBar1”的线程访问它。 } }}