1. 程式人生 > >c#多執行緒操作測試(阻塞執行緒,結束任務)

c#多執行緒操作測試(阻塞執行緒,結束任務)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class
Form5 : Form { public Form5() { InitializeComponent(); } string aa = "aaaa"; bool bl = false; private object syncstate = new object(); TaskScheduler scheduler = null; System.Timers.Timer tmPulse = new System.Timers.Timer();//
位置重新整理 System.Timers.Timer tmPulse1 = new System.Timers.Timer();//位置重新整理 Thread t; Thread t1; Thread t2; private void Form5_Load(object sender, EventArgs e) { scheduler = TaskScheduler.FromCurrentSynchronizationContext(); t = new Thread(new
ThreadStart(SetData)); t.IsBackground = true; t.Start(); t1 = new Thread(new ThreadStart(Set1)); t1.IsBackground = true; t1.Start(); t2 = new Thread(new ThreadStart(Set2)); t2.IsBackground = true; t2.Start(); } void Set() { tmPulse.Interval = 200; tmPulse.AutoReset = true;//設定是執行一次(false)還是一直執行(true); 位置重新整理 tmPulse.Start(); tmPulse.Elapsed += (o, a) => { SetData(); }; tmPulse.Enabled = true; tmPulse1.Interval = 200; tmPulse1.AutoReset = true;//設定是執行一次(false)還是一直執行(true); 位置重新整理 tmPulse1.Start(); tmPulse1.Elapsed += (o, a) => { Set1(); }; tmPulse1.Enabled = true; } void SetData() { while (true) { for (int i = 0; i < 10; i++) { if (i == 2) { } Task.Factory.StartNew(() => { lock (syncstate) { textBox1.Text += ("測試:" + aa + " " + i + "\r\n"); textBox1.SelectionStart = textBox1.Text.Length; this.textBox1.ScrollToCaret(); } }, CancellationToken.None, TaskCreationOptions.None, scheduler); Thread.Sleep(1000); aa = "第一個測試"; if (i == 5) { } } return; } } void Set1() { while (true) { for (int i = 0; i < 10; i++) { Task.Factory.StartNew(() => { lock (syncstate) { textBox1.Text += ("設定1:" + aa + " " + i + "\r\n"); textBox1.SelectionStart = textBox1.Text.Length; this.textBox1.ScrollToCaret(); } }, CancellationToken.None, TaskCreationOptions.None, scheduler); aa = "第1個設定" + i; Thread.Sleep(500); } Task.Factory.StartNew(() => { lock (syncstate) { textBox1.Text += ("設定1:完成\r\n"); textBox1.SelectionStart = textBox1.Text.Length; this.textBox1.ScrollToCaret(); } }, CancellationToken.None, TaskCreationOptions.None, scheduler); return; } } void Set2() { while (!bl) { for (int i = 0; i < 10; i++) { Task.Factory.StartNew(() => { lock (syncstate) { textBox1.Text += ("設定2:" + aa + " " + i + "\r\n"); textBox1.SelectionStart = textBox1.Text.Length; this.textBox1.ScrollToCaret(); } }, CancellationToken.None, TaskCreationOptions.None, scheduler); aa = "第2個設定" + i; Thread.Sleep(500); } } } private void button1_Click(object sender, EventArgs e) { bl = true; } private void Form5_FormClosed(object sender, FormClosedEventArgs e) { t.Abort(); t.Join(); t1.Abort(); t1.Join(); t2.Abort(); t2.Join(); } } }