https://dotblogs.com.tw/yc421206/2010/10/24/18546
https://dotblogs.com.tw/brooke/2015/10/12/153547
https://ithelp.ithome.com.tw/articles/10195452?sc=rss.qu
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Timers;
using System.Windows.Forms;
//匯入命名空間
using ThreadingTimer = System.Threading.Timer;
using TimersTimer = System.Timers.Timer;
namespace ThreadTimer
{
public partial class Form1 : Form
{
//程式開始
ThreadingTimer _ThreadTimer = null;
TimersTimer _TimersTimer = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Thread t = Thread.CurrentThread;
bool IsThreadPool = t.IsThreadPoolThread;
bool IsBackground = t.IsBackground;
t.Name = "Main Thread";
string msg = string.Format("Thread[{0}]:{1},Is ThreadPool=[{2}],Is Background=[{3}]", t.ManagedThreadId, t.ThreadState, IsThreadPool, IsBackground);
this.Text = msg;
}
private void button2_Click(object sender, EventArgs e)
{
this._TimersTimer = new TimersTimer();
this._TimersTimer.Interval = 100;
this._TimersTimer.Elapsed += new System.Timers.ElapsedEventHandler(_TimersTimer_Elapsed);
this._TimersTimer.Start();
}
private void _TimersTimer_Elapsed(object sender, ElapsedEventArgs e)
{
Thread t = Thread.CurrentThread;
bool IsThreadPool = t.IsThreadPoolThread;
bool IsBackground = t.IsBackground;
string msg = string.Format("Thread[{0}]:{1},Is ThreadPool=[{2}],Is Background=[{3}]", t.ManagedThreadId, t.ThreadState, IsThreadPool, IsBackground);
if (this.listBox2.InvokeRequired)
{
listBox2.Invoke(new Action<string>(s => {
this.listBox2.Items.Add(s);
}), msg);
}
else
{
this.listBox2.Items.Add(msg);
}
}
private void button1_Click(object sender, EventArgs e)
{
string currentName = new StackTrace(true).GetFrame(0).GetMethod().Name;
//TimerCallback委派可用來指定 Timer 呼叫的方法, 1.等多久再開始 100.隔多久反覆執行
this._ThreadTimer = new ThreadingTimer( new System.Threading.TimerCallback(CallbackMethod), currentName, 1, 100);
}
void CallbackMethod(object State)
{
string methodName = State.ToString();
Thread t = Thread.CurrentThread;
bool IsThreadPool = t.IsThreadPoolThread;
bool IsBackground = t.IsBackground;
string msg = string.Format("Thread[{0}]:{1},Is ThreadPool=[{2}],Is Background=[{3}]", t.ManagedThreadId, t.ThreadState, IsThreadPool, IsBackground);
this.BeginInvoke(new UpdateControl(_mUpdateControl), new object[] { this.listBox1, msg });
}
delegate void UpdateControl(Control Ctrl, string Msg);
private object _objLock = new object();
void _mUpdateControl(Control Ctrl, string Msg)
{
//多執行續同時進行時,叫用這個方法時,看有沒有被lock,如有被lock,等他然後再跑裡面的東西
lock (this._objLock)
{
if (Ctrl is ListBox)
((ListBox)Ctrl).Items.Add(Msg);
}
}
}
}
沒有留言:
張貼留言