C#线程间操作
求一个简单的线程间操作:我有一个线程在窗体load时启动。我怎么通过两个按钮来控制这个线程的启动与停止?不用Suspend!各位帮帮忙,请问怎么实现?
[解决办法]
- C# code
using System;using System.Threading;using System.Windows.Forms;namespace WindowsFormsApplication1{ public partial class Form1 : Form { private Boolean _bStartThread; private Int64 _total; public Form1() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; _bStartThread = false; _total = 0; } private void Run() { if (!_bStartThread) { _bStartThread = true; Thread thread = new Thread(new ThreadStart(ThreadFun)); thread.IsBackground = true; thread.Start(); } } private void ThreadFun() { while (_bStartThread) { Interlocked.Increment(ref _total); this.Text = _total.ToString(); } } private void button1_Click(object sender, EventArgs e) { Run(); } private void button2_Click(object sender, EventArgs e) { _bStartThread = false; } }}