task 子线程处理队列数据
模拟多线程处理数据的时间
namespace reportfile.MultiThread { public delegate void DelegateShowStateInfo(string state); public class TestThread { private Queue<QueueInfo> _ListQueue; private bool _Exit = false;//线程是否退出 private static Form _OwnerForm; //測試的窗體 private DelegateShowStateInfo _StateMethod; public TestThread(Form sender, DelegateShowStateInfo method) { _StateMethod = method; _OwnerForm = sender; } public void HandelData() { Task.Factory.StartNew(new Action(() => { Start();//启动后台线程 for (int index = 1; index <= 10; index++)//PageIndex { try { //队列有数据等于3的时候休眠3秒 while (_ListQueue.Count >= 3) { Thread.Sleep(1000); } //模拟获取数据 Thread.Sleep(3000); _ListQueue.Enqueue(new QueueInfo() { code = index.ToString() }); } catch (Exception Ex) { Console.Write(Ex.Message.ToString()); } } _Exit = false; })); } public void Start()//启动 { _ListQueue = new Queue<QueueInfo>();//队列 _Exit = true; //Task task = new Task(() => threadStart()); //task.Start(); Thread thread = new Thread(threadStart); thread.IsBackground = true; thread.Start(); //thread.Join(); } private void threadStart() { while (_Exit) { while (_ListQueue.Count > 0) { try { //从队列中取出 QueueInfo queueinfo = _ListQueue.Dequeue(); //模拟处理数据 Parallel.For 处理数据 Thread.Sleep(3000); if (_OwnerForm != null) { _OwnerForm.Invoke(_StateMethod, queueinfo.code); Application.DoEvents(); } } catch (Exception ex) { Console.Write("队列:" + ex.Message.ToString()); } } } if (!_Exit) { if (_OwnerForm != null) { _OwnerForm.Invoke(_StateMethod, "结束"); Application.DoEvents(); } } } } }
窗体调用
private TestThread _testThread; public frmMultiThreading() { InitializeComponent(); } private void frmMultiThreading_Load(object sender, EventArgs e) { _testThread = new TestThread(this, ShowData); } private void ShowData(string state) { this.BeginInvoke(new Action(() => { textBox1.Text += state + " "; })); } private void button1_Click(object sender, EventArgs e) { _testThread.HandelData(); }
效果