下面是我学习C#事件调用的代码,以及其中使用线程的情况。我在使用过程中有几个疑问:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace EventSample1
{
public class MyTimerClass
{
public event EventHandler MyElapsed;
//----
private void OnOneSecond(object source, EventArgs args)
{
if (MyElapsed != null)
{
MyElapsed(source, args);
}
}
//----
private System.Timers.Timer MyPrivateTimer;
//----
public MyTimerClass()
{
MyPrivateTimer = new System.Timers.Timer();
MyPrivateTimer.Elapsed += OnOneSecond;
//----
MyPrivateTimer.Interval = 1000;
MyPrivateTimer.Enabled = true;
}
}
//----
class classA
{
public void TimerHandlerA(object source, EventArgs args)
{
Console.WriteLine("{0} class A handler called! at thread {1}", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
}
}
class classB
{
public static void TimerHandlerB(object source, EventArgs args)
{
Console.WriteLine("{0} class B handler called! at thread {1}", DateTime.Now, Thread.CurrentThread.ManagedThreadId);
}
}
//----
class Program
{
static void Main()
{
Console.WriteLine("Main thread on {0}", Thread.CurrentThread.ManagedThreadId);
classA ca = new classA();
MyTimerClass mc = new MyTimerClass();
//----
mc.MyElapsed += ca.TimerHandlerA;
mc.MyElapsed += classB.TimerHandlerB;
//----
Thread.Sleep(2250);
}
}
}
the results is like this:
这表明当mc.Elapsed
被调用时,主线程打开另一个(invoke?)线程执行两个EventHandler(TimerEventHandler
A 和 B)。
我的问题1。就是它:
为什么主线程被标记为No.1,而新调用的线程被标记为No.4?
那么,2号线和3号线是什么?
他们在做什么?
然后我更改了 main() 中的代码,让主线程休眠时间从 2.25 秒变为 5.25 秒,
Thread.Sleep(5250);
我得到了不同的结果(另一个线程被调用 ):
我的问题2。就是它:
使用的线程数完全由系统决定吗?是人们所说的“线程池”来做到这一点吗?
之后,我在之前插入另一行Thread.Sleep()
看看会发生什么?
//----
mc.MyElapsed += ca.TimerHandlerA;
mc.MyElapsed += classB.TimerHandlerB;
Console.ReadLine();
//----
Thread.Sleep(2250);
我这样做的原因是:
据我了解,当事件 myElapsed 被调用时,A 和 B 将被调用。在调用它们之前,程序将使用一个新线程来执行中的代码TimerEventHandler
A和B。主线程很快就会回到readline()
排队等待我们输入。就像我们使用的时候一样Thread.Sleep()
,主线程刚刚回到Thread.Sleep()
并在2.25秒后关闭正在运行的程序!
But the result is NOT like what we think, the TimerEventHandler
A and B just be called again and again......like the main thread will never come to readline()
!
我只是在同一个位置使用不同的线,为什么结果如此不同?
我想这可能涉及到线程中的一些细节,但是我的书并没有太多谈论C#中线程的使用,有人可以推荐另一本自学的好书吗?
提前致谢!