在C#中我们往往喜欢多开线程,有些线程我们是写完就不管了,有时候不知道有没有执行,但是在debug的时候想在页面上监控线程数量,心中对自己写的程序有个谱。
话不多说,查看线程数量代码如下:
Process myProcess = Process.GetCurrentProcess();//获取该进程
ProcessThreadCollection PTC = myProcess.Threads;//获取其关联的线程,包括主线程
//int num = 0;
//foreach (ProcessThread item in PTC)
//{
// if (item.ThreadState == System.Diagnostics.ThreadState.Wait)
// if (item.WaitReason == ThreadWaitReason.UserRequest)
// continue;
// num++;
//}
int num = PTC.Count;//获取线程数量
然后创建定时器代码如下:
DispatcherTimer timer = new DispatcherTimer();
timer.Tick += new EventHandler(timer_Tick);
timer.Interval = TimeSpan.FromSeconds(0.1); //设置刷新的间隔时间
timer.Start();
每0.1s执行一次timer_Tick函数,然后把需要更新显示的代码封装进去:
private void timer_Tick(object sender, EventArgs e)
{
Process myProcess = Process.GetCurrentProcess();//获取该进程
ProcessThreadCollection PTC = myProcess.Threads;//获取其关联的线程,包括主线程
//int num = 0;
//foreach (ProcessThread item in PTC)
//{
// if (item.ThreadState == System.Diagnostics.ThreadState.Wait)
// if (item.WaitReason == ThreadWaitReason.UserRequest)
// continue;
// num++;
//}
int num = PTC.Count;//获取线程数量
LthreadNum.Content = num.ToString();
}
其中LthreadNum是WPF里面的一个Label控件,然后就可以在界面上看到线程数了。
注意这里并不需要用到Involve,个人猜测应该是定时器时间到了,就把事情交给UI线程,UI空闲就去执行了。
因为在timer_Tick中添加一句Thread.Sleep(95);
能够明显感觉到UI卡顿。